skip to content

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).

strategy =
input, in table order
20001view
20002add_to_cart
20003click
20004purchase
20005view
20006purchase
20007click
20008view
20009view
20010add_to_cart
20011click
20012add_to_cart
hash table: one counter per kind
·
handed up to the next node
nothing yet

an empty hash table. rows come in whatever order the scan finds them.

row 1/14
model of the two strategies, on twelve real rows; the counts match postgres's GROUP BY
real output, postgres 18.6 (PGlite 0.5.12) · aggregation
twelve real events, grouped by kind, both ways. step through. HashAggregate keeps a counter per kind and hands everything up at the end. GroupAggregate needs the rows sorted, keeps one counter, and hands each group up as soon as the next kind starts.

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:

plan =
query.sql
  1. 1EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
  2. 2SELECT user_id, count(*) FROM events GROUP BY user_id
what postgres printed
  1. HashAggregate (actual rows=500.00 loops=1)
  2. Group Key: user_id
  3. Batches: 1 Memory Usage: 53kB
  4. Buffers: shared hit=2 read=333
  5. -> Seq Scan on events (actual rows=25000.00 loops=1)
  6. 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.

real output, postgres 18.6 (PGlite 0.5.12) · aggregation
the same GROUP BY three ways. with nothing sorted by user_id, postgres hashes (53kB). switch hash aggregation off and it sorts all 25,000 rows first. give it an index on user_id and the rows arrive sorted for free: a GroupAggregate with no Sort at all.

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.

predict the output
GROUP BY user_id ORDER BY user_id, no index. what does postgres sort?
sql
SELECT user_id, count(*)
FROM events
GROUP BY user_id
ORDER BY user_id;
sqldb=events
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT user_id, count(*)
FROM events
GROUP BY user_id
ORDER BY user_id;
output, from postgres 18.6
EXPLAIN
Sort (actual rows=500.00 loops=1) Sort Key: user_id Sort Method: quicksort Memory: 32kB Buffers: shared hit=3 read=335 -> HashAggregate (actual rows=500.00 loops=1) Group Key: user_id Batches: 1 Memory Usage: 53kB Buffers: shared read=335 -> Seq Scan on events (actual rows=25000.00 loops=1) Buffers: shared read=335 Planning: Buffers: shared hit=46 read=4

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:

sqldb=events
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT kind, user_id, count(*)
FROM events
GROUP BY ROLLUP (kind, user_id);
output, from postgres 18.6
EXPLAIN
MixedAggregate (actual rows=2441.00 loops=1) Hash Key: kind, user_id Hash Key: kind Group Key: () Batches: 1 Memory Usage: 265kB Buffers: shared read=335 -> Seq Scan on events (actual rows=25000.00 loops=1) Buffers: shared read=335 Planning: Buffers: shared hit=61 read=5

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.

work_mem =
query.sql
  1. 1EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
  2. 2SELECT user_id, count(*), sum(amount) FROM events GROUP BY user_id
what postgres printed
  1. HashAggregate (actual rows=500.00 loops=1)
  2. Group Key: user_id
  3. Batches: 1 Memory Usage: 189kB
  4. Buffers: shared hit=335
  5. -> Seq Scan on events (actual rows=25000.00 loops=1)
  6. Buffers: shared hit=335
kB written to disk (Disk Usage)
0 kB
240 kB

the default 4MB: a sum and a count per user, all 500 groups in one hash table.

real output, postgres 18.6 (PGlite 0.5.12) · aggregation
a count and a sum per user at the default work_mem and at 64kB. at 64kB the table can't hold all 500 groups: 5 batches, 240kB written to disk, and the same 500 rows at the end.

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:

sqldb=events
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE TABLE
#3 · CREATE TABLE
#4 · CREATE TABLE
#5 · INSERT 0 25000
#6 · ANALYZE
#7 · SET
#8 · EXPLAIN
Finalize GroupAggregate (actual rows=5.00 loops=1) Group Key: ev.kind -> Sort (actual rows=14.00 loops=1) Sort Key: ev.kind Sort Method: quicksort Memory: 17kB -> Append (actual rows=14.00 loops=1) -> Partial HashAggregate (actual rows=5.00 loops=1) Group Key: ev.kind Batches: 1 Memory Usage: 32kB -> Seq Scan on ev_mar ev (actual rows=8517.00 loops=1) -> Partial HashAggregate (actual rows=5.00 loops=1) Group Key: ev_1.kind Batches: 1 Memory Usage: 32kB -> Seq Scan on ev_apr ev_1 (actual rows=7966.00 loops=1) -> Partial HashAggregate (actual rows=4.00 loops=1) Group Key: ev_2.kind Batches: 1 Memory Usage: 32kB -> Seq Scan on ev_may ev_2 (actual rows=8517.00 loops=1)

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.

quick check
which aggregate can't be split into Partial and Finalize?

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.