opyeb SQLPlan

Guides · Nodes

When a sort spills to disk, and the three ways to stop it

Updated 28 Nov 2026 · 7 min read

A Sort node needs all its input before it can return the first row, unless it is a top-N sort for a small LIMIT. PostgreSQL gives the sort a memory allowance from work_mem. If the rows fit, it uses quicksort in memory. If they do not, it switches to external merge: it sorts chunks that fit, writes each chunk to a temporary file, and merges the chunks while reading them back. That is the disk spill the plan reports as a Sort Method and a Disk size.

The plan line looks like Sort Method: external merge Disk: 48000kB. The 48 MB is the total size of the temporary runs, not the size of the result. Temp read and temp written blocks in the Buffers line usually accompany it. A spill turns a memory operation into sequential writes and reads, and on a busy server it also competes for I/O with everything else.

Sort MethodWhen usedCost
quicksortFits in work_memMemory and CPU only
top-N heapsortSmall LIMIT with ORDER BYKeeps only N rows in memory
external mergeDoes not fit in work_memWrites and reads temporary files

The sort is often avoidable

The best fix is usually an index that returns rows in the required order. A B-tree on the sort key, or on a filter column followed by the sort key, lets the scan produce rows already ordered, and the Sort node disappears. For a query with a LIMIT, the scan can stop after N rows, which is far cheaper than sorting a million. The right composite order is equality columns first, then the sort column.

The second fix is to sort fewer rows. Pushing a selective filter below the sort, projecting fewer columns, or aggregating earlier reduces the row count and the row width. A sort of 10,000 narrow rows fits where a sort of 1,000,000 wide rows does not. The plan shows this as a smaller row count on the Sort's child, and the Disk size shrinks or disappears.

When work_mem is the right lever

Sometimes the sort is genuinely needed and the rows genuinely do not fit. A report that orders a large result, or a merge join that needs both inputs sorted, may have no index alternative. Raising work_mem for that statement with SET LOCAL work_mem = '256MB' inside a transaction is a targeted change that does not affect other sessions. A global increase multiplies across concurrent queries and can exhaust memory.

Watch the interaction with parallelism. Each worker gets its own work_mem allowance for a sort, so a parallel sort can use several times the nominal value. The plan shows workers and their loops; a spill under a Gather node may need more memory than the label suggests. Size the change for the worst concurrent case, not for the single query you are testing.

Sorts that are not the problem

A small quicksort of a few hundred rows is not worth optimising, even if it appears in the plan. The analyzer flags only sorts that spill. A sort of 24 kB in memory costs microseconds and removing it with an index may add write cost elsewhere. Optimise the sorts that appear with Disk or temp blocks, or that sit under a node with a large self time.

A top-N heapsort is also usually fine. It keeps only N rows and is designed for the LIMIT case. If a top-N sort shows a large disk size, the limit is probably large or the rows are very wide, and an index on the sort key is the better answer.

A fix order

  1. Confirm the sort is spilling: check Sort Method, Disk and temp blocks.
  2. See whether an index on the sort key, combined with the filter, can supply the order.
  3. Reduce the rows or width before the sort with a filter or a narrower projection.
  4. If neither is possible, raise work_mem for this statement only and measure.
  5. Re-run EXPLAIN ANALYZE and confirm the method is quicksort or the Sort node is gone.

The analyzer reports a sort with an external method or a disk size as a high finding and shows the disk size in the detail row. It cannot know whether the sort is avoidable; that depends on the query and the indexes. The finding is a pointer to the node, not a prescription for work_mem.

A spill is a design signal before it is a memory signal. Ask why the rows must be sorted in memory at all.

Sources

Questions

What is the difference between quicksort and external merge?

Quicksort sorts in memory and is used when the data fits in work_mem. External merge writes sorted runs to temporary files and merges them, which is much slower. Top-N heapsort is used for a small LIMIT and keeps only the first N rows in memory.

Is raising work_mem always the answer?

No. It is a per-operation allowance, so many concurrent sorts can multiply memory use and push the server into swapping. It also hides the design problem when an index could return rows in order. Raise it deliberately, with a per-query SET rather than a global change, and measure the effect.

Why does a small LIMIT still spill?

A LIMIT with an ORDER BY can use top-N heapsort only when the sort fits its memory. If the input rows are wide or the limit is large, the planner may still spill. An index on the sort key with the filter columns can return the first rows directly, which is usually better than any sort.

Load the disk-spill sample and look at the Sort node's method and 48 MB of disk.

Open the analyzer

Written against the PostgreSQL and MySQL documentation and the standard cost model; every plan in the examples can be pasted into the analyzer linked above.

Back to the guides