skip to content

sorting and work_mem

quicksort in memory, top-N heapsort for LIMIT, external merge on disk, and Incremental Sort.

address
everything.execution.sorting
part
part 9, how a query runs
chapter
chapter 11 of 13
reading time
8 min

a Sort node picks its algorithm when it runs, by how much fits in work_mem. everything fits: quicksort in memory. a LIMIT on top: a top-N heapsort that only ever keeps the best n rows. too big: an external merge, which sorts runs that fit, writes them to temp files and merges them.

and if the rows already arrive sorted on the first keys, an Incremental Sort only sorts within each group of equal leading keys.

the picture

you know how EXPLAIN ANALYZE sometimes says Sort Method: quicksort Memory: 1684kB and sometimes external merge Disk: 1040kB for the same ORDER BY? the query didn't change. the room did.

think of sorting a pile of exam papers on a desk. if the pile fits on the desk, spread them out and sort them (quicksort). if you only need the top 10, keep a stack of 10 and swap in any paper that beats the worst one in it (a heap). if the pile is bigger than the desk, sort one deskful at a time into neat stacks on the floor, then merge the stacks by repeatedly taking the best top paper (external merge).

the events table, 25,000 rows, sorted by kind and newest first, at three sizes of desk:

query =
work_mem =
query.sql
  1. 1SET work_mem = '4MB';
  2. 2EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
  3. 3SELECT id, user_id, kind, occurred_at FROM events ORDER BY kind, occurred_at DESC
what postgres printed
  1. Sort (actual rows=25000.00 loops=1)
  2. Sort Key: kind, occurred_at DESC
  3. Sort Method: quicksort Memory: 1684kB
  4. Buffers: shared hit=6 read=335
  5. -> Seq Scan on events (actual rows=25000.00 loops=1)
  6. Buffers: shared read=335
kB the sort used (Memory or Disk)
1,684 kB
18 kB
1,040 kB
18 kB
1,080 kB
18 kB

4MB of work_mem: all 25,000 rows fit, so they're sorted in memory with quicksort.

real output, postgres 18.6 (PGlite 0.5.12) · sorting
pick a query and a work_mem. without a LIMIT, 4MB fits all 25,000 rows in memory and anything less spills to disk. with LIMIT 10, the sort keeps 10 rows in 18kB whatever work_mem is. the bar is the kB each sort used, in memory or on disk.

the 1,684kB in memory became 1,040kB on disk at 1MB: in memory every row also carries some bookkeeping, on disk it is packed tight. at 64kB it's more runs, each a sliver of memory's worth, so more merging and more temp traffic (289 pages written instead of 131) for the same rows.

quicksort

sqldb=events
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, user_id, kind, occurred_at
FROM events
ORDER BY kind, occurred_at DESC;
output, from postgres 18.6
EXPLAIN
Sort (actual rows=25000.00 loops=1) Sort Key: kind, occurred_at DESC Sort Method: quicksort Memory: 1684kB Buffers: shared hit=6 read=335 -> Seq Scan on events (actual rows=25000.00 loops=1) Buffers: shared read=335 Planning: Buffers: shared hit=65 read=5

the whole input goes into memory, then gets sorted, then the first row comes out. that's why a Sort is a blocking node: its first row could be anybody. Memory: 1684kB is the peak, and it has to be under work_mem (4MB by default, per sort, per query, so a query with three Sorts can use three times that).

top-N heapsort

with a LIMIT above it, postgres tells the Sort how many rows it'll ever be asked for. the sort keeps a heap of the best n so far: each new row is compared with the worst of the n, and either thrown away or swapped in. 25,000 rows go through it; 10 are ever held.

predict the output
ORDER BY ... LIMIT 10 over 25,000 rows, work_mem = 64kB. what happens?
sql
SET work_mem = '64kB';
SELECT id, user_id, kind, occurred_at
FROM events
ORDER BY kind, occurred_at DESC
LIMIT 10;

external merge

when the rows don't fit, postgres fills work_mem, sorts what it has, writes it out as a sorted run, and starts again. at the end it merges the runs: one cursor per run, and the next output row is always the smallest row under any cursor. with a tiny pile and a desk that holds four:

input
42
0
7
1
19
2
88
3
3
4
61
5
25
6
14
7
90
8
8
9
33
10
56
11

the input: 12 values, and memory that holds 4.

step 1/5
drawn by hand · a textbook model, not a capture
a model of an external sort with room for 4 values, on 12. step through: three runs, each sorted in memory and written out, then one merge with a cursor per run. the hot value is the smallest under the cursors, the next one out.

postgres does the same with many more runs and a heap of cursors instead of a row of them, and if there are too many runs to merge at once it merges them in rounds. in the plan, it's Sort Method: external merge Disk: 1040kB, and the temp files show up under Buffers: as temp read and temp written, counted in 8 KB pages:

sqldb=events
SET work_mem = '1MB';
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, user_id, kind, occurred_at
FROM events
ORDER BY kind, occurred_at DESC;
output, from postgres 18.6
#1 · SET
#2 · EXPLAIN
Sort (actual rows=25000.00 loops=1) Sort Key: kind, occurred_at DESC Sort Method: external merge Disk: 1040kB Buffers: shared hit=6 read=335, temp read=130 written=131 -> Seq Scan on events (actual rows=25000.00 loops=1) Buffers: shared read=335 Planning: Buffers: shared hit=65 read=5

an external sort isn't a disaster: it's sequential writes and reads of files the OS will often keep in its cache. it's just slower than not doing it, and it's the first thing to look for when a big ORDER BY, a merge join or a DISTINCT is slow. log_temp_files logs every temp file over a size you pick, which is how you find them in production.

incremental sort pg 13+

sometimes the rows already arrive sorted on the first key you asked for. an index on user_id hands rows over by user, so ORDER BY user_id, occurred_at only has to sort each user's few dozen events among themselves:

sqldb=events
CREATE INDEX ON events (user_id);
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, user_id, occurred_at
FROM events
ORDER BY user_id, occurred_at
LIMIT 10;
output, from postgres 18.6
#1 · CREATE INDEX
#2 · EXPLAIN
Limit (actual rows=10.00 loops=1) Buffers: shared hit=337 read=3 -> Incremental Sort (actual rows=10.00 loops=1) Sort Key: user_id, occurred_at Presorted Key: user_id Full-sort Groups: 1 Sort Method: top-N heapsort Average Memory: 17kB Peak Memory: 17kB Pre-sorted Groups: 1 Sort Method: top-N heapsort Average Memory: 17kB Peak Memory: 17kB Buffers: shared hit=337 read=3 -> Index Scan using events_user_id_idx on events (actual rows=1135.00 loops=1) Index Searches: 1 Buffers: shared hit=331 read=3 Planning: Buffers: shared hit=70 read=6
index on user_id =
query.sql
  1. 1RESET work_mem;
  2. 2EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
  3. 3SELECT id, user_id, occurred_at FROM events ORDER BY user_id, occurred_at LIMIT 10
what postgres printed
  1. Limit (actual rows=10.00 loops=1)
  2. Buffers: shared hit=338
  3. -> Sort (actual rows=10.00 loops=1)
  4. Sort Key: user_id, occurred_at
  5. Sort Method: top-N heapsort Memory: 18kB
  6. Buffers: shared hit=338
  7. -> Seq Scan on events (actual rows=25000.00 loops=1)
  8. Buffers: shared hit=335
rows the scan handed up
25,000 rows
1,135 rows

no index: sorting by user_id, occurred_at means reading all 25,000 rows into a top-N heapsort.

real output, postgres 18.6 (PGlite 0.5.12) · sorting
the same ORDER BY user_id, occurred_at LIMIT 10, before and after an index on user_id. without it, a top-N heapsort has to see all 25,000 rows. with it, an Incremental Sort sorts one user's events at a time and stops once it has 10. the bar is the rows the scan handed up.

Presorted Key: user_id. the Incremental Sort reads one group of equal user_ids at a time from the index, sorts that group on occurred_at, and hands it up. with a LIMIT, that means it stops early: the index scan returned 1,135 rows, not 25,000, because 10 rows were done long before the last user. a plain Sort would have read and sorted all of them first. (the Full-sort Groups and Pre-sorted Groups lines are its own accounting: it batches small groups together and sorts them as one.)

quick check
what decides between quicksort and external merge?

keylines

  • fits in work_mem: quicksort, in memory.
  • LIMIT n above it: top-N heapsort, holding only n rows.
  • doesn't fit: external merge, sorted runs in temp files, merged at the end.
  • the method is chosen while the sort runs, by size, not by the planner.
  • already sorted on the leading keys: Incremental Sort sorts group by group and can stop early.