Cookbook recipe

Stop disk-spilled sorts by tuning work_mem

Applies to PostgreSQL 13–17 Last reviewed May 2026 Grounded in source
Estimated investigation4 min

Scenario

EXPLAIN shows "Sort Method: external merge Disk". The sort did not fit in memory and spilled to disk, making it slow. Diagnose it Look for external sorts/hashes: EXPLAIN (ANALYZE) SELECT ... ORDER BY ...; -- Sort…

Investigation Path

EXPLAIN shows “Sort Method: external merge Disk”. The sort did not fit in memory and spilled to disk, making it slow.

Diagnose it

Look for external sorts/hashes:

EXPLAIN (ANALYZE)
SELECT ... ORDER BY ...;
-- Sort Method: external merge  Disk: 124032kB

Why it happens

Each sort/hash node gets up to work_mem. When the data exceeds it, PostgreSQL spills to temp files on disk. Too-low work_mem causes spills; too-high risks OOM because every node and connection can use it.

This is a Pro lesson

Get every Learning Pathway and cookbook recipe — grounded in PostgreSQL source code, with diagnostics, fixes, and prevention for each topic.

Continue this lesson to learn:

  • How to fix it
  • Prevent it next time
  • Related & next steps
  • All 36 Learning Pathway lessons
  • 170+ cookbook recipes
  • Source-grounded diagnostics & fixes

Secure checkout Cancel anytime Source-grounded

Career Impact

This scenario builds production judgment and operational confidence under pressure.

Open Career Dashboard →

Keep going

Related & next steps

Was this helpful?

← All cookbook recipes