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:
- 1SET work_mem = '4MB';
- 2EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 3SELECT id, user_id, kind, occurred_at FROM events ORDER BY kind, occurred_at DESC
- 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
4MB of work_mem: all 25,000 rows fit, so they're sorted in memory with quicksort.
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
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, user_id, kind, occurred_at
FROM events
ORDER BY kind, occurred_at DESC;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.
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:
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:
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;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:
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;- 1RESET work_mem;
- 2EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 3SELECT id, user_id, occurred_at FROM events ORDER BY user_id, occurred_at LIMIT 10
- Limit (actual rows=10.00 loops=1)
- Buffers: shared hit=338
- -> Sort (actual rows=10.00 loops=1)
- Sort Key: user_id, occurred_at
- Sort Method: top-N heapsort Memory: 18kB
- Buffers: shared hit=338
- -> Seq Scan on events (actual rows=25000.00 loops=1)
- Buffers: shared hit=335
no index: sorting by user_id, occurred_at means reading all 25,000 rows into a top-N heapsort.
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.)
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.