how GROUP BY runs
HashAggregate vs GroupAggregate, and the hash table that spills to disk.
- address
- everything.execution.aggregation_algorithms
- part
- part 9, how a query runs
- chapter
- chapter 12 of 13
- reading time
- 8 min
postgres runs a GROUP BY one of two ways. HashAggregate reads the rows in any order and keeps a hash table with one entry per group; nothing comes out until the input ends. GroupAggregate needs its input sorted on the group key, and hands each group up the moment the key changes.
a hash table that outgrows work_mem spills to disk in batches (since postgres 13). and an aggregate can be split in two, Partial then Finalize, so pieces of the table can be grouped separately and combined.
the picture
you know how GROUP BY sometimes adds a Sort to the plan and sometimes doesn't? same as counting votes. you can keep a tally sheet with a line per candidate and mark each ballot as it comes (a hash table). or, if the ballots arrive sorted by candidate, you just count until the name changes, write the total down, and start again (a sorted group).
an empty hash table. rows come in whatever order the scan finds them.
the tally sheet needs memory for every group at once, and works on any input. the sorted count needs memory for one group, and needs sorted input. that's the whole trade-off, and the planner prices both.
three plans for one GROUP BY
events per user, 25,000 rows into 500 groups:
- 1EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 2SELECT user_id, count(*) FROM events GROUP BY user_id
- HashAggregate (actual rows=500.00 loops=1)
- Group Key: user_id
- Batches: 1 Memory Usage: 53kB
- Buffers: shared hit=2 read=333
- -> Seq Scan on events (actual rows=25000.00 loops=1)
- Buffers: shared hit=2 read=333
events per user. nothing is sorted by user_id, so postgres hashes: one pass, one hash table entry per user.
hashing 25,000 rows into 500 entries is cheap, cheaper than sorting 25,000 rows (513kB of quicksort) just to count them. but sorted input you already have is free, and the GroupAggregate over the index needs no hash table and streams its groups, which also means a LIMIT above it can stop it early. the sort order an index provides is the same resource a merge join spends.
SELECT user_id, count(*)
FROM events
GROUP BY user_id
ORDER BY user_id;EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT user_id, count(*)
FROM events
GROUP BY user_id
ORDER BY user_id;MixedAggregate
ROLLUP and GROUPING SETS ask for several groupings in one query. postgres can do them all in one pass over the input, with one hash table per grouping, and the grand total () needs no table at all, just a running total. a mix of hashed and plain groupings is a MixedAggregate:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT kind, user_id, count(*)
FROM events
GROUP BY ROLLUP (kind, user_id);two Hash Key: lines (kind and user_id together, then kind alone) and a Group Key: (): 2,441 rows out of one scan.
when the hash table doesn't fit pg 13+
a HashAggregate's table gets work_mem × hash_mem_multiplier, like a hash join's. before postgres 13, a HashAggregate that had been planned kept growing in memory however wrong the estimate was. since 13, it spills: groups already in the table keep being updated, rows for new groups that don't fit are written to temp files, and those are aggregated in later batches.
- 1EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 2SELECT user_id, count(*), sum(amount) FROM events GROUP BY user_id
- HashAggregate (actual rows=500.00 loops=1)
- Group Key: user_id
- Batches: 1 Memory Usage: 189kB
- Buffers: shared hit=335
- -> Seq Scan on events (actual rows=25000.00 loops=1)
- Buffers: shared hit=335
the default 4MB: a sum and a count per user, all 500 groups in one hash table.
Batches: 5 Memory Usage: 144kB Disk Usage: 240kB. three numbers to read: more than one batch means it spilled, memory usage is the peak (here a little over the 128kB budget), and disk usage is what went to temp files. same as a spilling sort or hash join, it's slower, not wrong.
partial and finalize
an aggregate like count(*) can be computed in pieces: count each piece, then add up the counts. postgres splits it into a Partial aggregate that runs on each piece and a Finalize that combines the partial results. the pieces can be parallel workers, each reading part of the table, but they don't have to be. partitions work too, and that runs right here:
CREATE TABLE ev (user_id int, kind text, occurred_at timestamptz) PARTITION BY RANGE (occurred_at);
CREATE TABLE ev_mar PARTITION OF ev FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');
CREATE TABLE ev_apr PARTITION OF ev FOR VALUES FROM ('2026-04-01') TO ('2026-05-01');
CREATE TABLE ev_may PARTITION OF ev FOR VALUES FROM ('2026-05-01') TO ('2026-06-01');
INSERT INTO ev SELECT user_id, kind, occurred_at FROM events ORDER BY id;
ANALYZE ev;
SET enable_partitionwise_aggregate = on;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT kind, count(*) FROM ev GROUP BY kind ORDER BY kind;each month is grouped on its own by a Partial HashAggregate (5, 5 and 4 kinds: one kind never happened in may), the 14 partial rows are appended and sorted, and a Finalize GroupAggregate adds up each kind's partial counts into 5 rows. for count the combine step is a sum; for avg each partial carries a sum and a count; for count(DISTINCT ...) there's no way to combine, so it can't be split.
keylines
- HashAggregate: a hash table entry per group, any input order, everything out at the end.
- GroupAggregate: sorted input, one group in memory, each group out as soon as the key changes.
- an index that provides the order makes GroupAggregate free; otherwise hashing usually wins.
- a hash table past work_mem × hash_mem_multiplier spills: Batches > 1, Disk Usage.
- Partial then Finalize: aggregate the pieces, then combine them. DISTINCT aggregates can't.