Sort and aggregation
Overview
Sort establishes an ordering; aggregation reduces groups to results. A hash aggregate keeps state per group, while a sorted aggregate can consume adjacent equal keys and finalize groups as they end.
First example
EXPLAIN QUERY PLAN SELECT customer_id,SUM(amount) FROM po_order NOT INDEXED GROUP BY customer_id;Observed SQLite result (rows in JSON):
[ [ 6, 0, 0, "SCAN po_order" ], [ 8, 0, 0, "USE TEMP B-TREE FOR GROUP BY" ]]How it works
The SQLite forced scan needs a temporary B-tree for GROUP BY, while the covering customer index supplies grouping order without that plan node. Both produce customer totals 250,350,100. The plan does not establish a disk spill. PostgreSQL HashAggregate needs state for distinct groups; GroupAggregate consumes ordered input, possibly from an index or Sort. External sorting creates sorted runs and merges them when memory is insufficient; exact spill behavior depends on the engine and workload. Hash aggregation does not promise ordered output. A WindowAgg computes over rows without collapsing them and may need partition/order sorting. For top-N queries a bounded sort may reduce memory, but still must consider relevant input unless access order permits stopping.
Practical example
EXPLAIN QUERY PLAN SELECT customer_id,SUM(amount) FROM po_order GROUP BY customer_id;Observed SQLite result (rows in JSON):
[ [ 6, 0, 0, "SCAN po_order USING COVERING INDEX po_customer_amount" ]]Practice and mistakes
Practice: execute the grouped sum with ORDER BY customer_id, both with NOT INDEXED and without it. Hint 1: inspect both plans. Hint 2: compare ordered rows, not execution time. Explain why customer 3 is absent.
PostgreSQL 17 example — NOT RUN
BEGIN;SET LOCAL statement_timeout='10s';SET LOCAL lock_timeout='2s';CREATE TEMP TABLE po_customer(id INTEGER PRIMARY KEY, name TEXT NOT NULL);INSERT INTO po_customer VALUES(1,'Ada'),(2,'Reza'),(3,'Sara'),(4,'Mina');CREATE TEMP TABLE po_order(id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES po_customer(id), amount INTEGER NOT NULL CHECK(amount>=0));INSERT INTO po_order VALUES(1,1,100),(2,1,150),(3,2,250),(4,2,50),(5,2,50),(6,4,100);CREATE INDEX po_customer_amount ON po_order(customer_id,amount);CREATE INDEX po_amount ON po_order(amount);
ANALYZE po_order;ANALYZE po_customer;EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) SELECT customer_id,SUM(amount) FROM po_order GROUP BY customer_id;SET LOCAL enable_hashagg=off;EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) SELECT customer_id,SUM(amount) FROM po_order GROUP BY customer_id;ROLLBACK;Expected result, not executed: "Compare aggregate strategies; totals 250,350,100."