CertGrid CertGrid
Troubleshooting·PostgreSQL

PostgreSQL work_mem and Sort Spill

A sort spills to disk at the default work_mem. Raising it to 128 MB keeps the sort in memory - and makes the query slower. The measurement is the lesson.

Performance Guide 37 of 47 Advanced

work_mem is per sort or hash per node per worker, not per query. A parallel query with several sorts can use many multiples of it, which is why raising it globally is riskier than it looks.

Every command on this page ran on db-a01.
Server NameIP AddressOSRolesCPURAMHDD
db-a01192.168.0.81Ubuntu 26.04 LTSPrimary / Source / Replica Set Member 12 Core4 GB50 GB

This guide includes

Use this when a sort is slow and you suspect it is spilling to disk. This matters because work_mem is per operation rather than per connection - and the spill is measurable both in the plan and server-wide.

Before you start

  1. Sort more than work_mem can hold

  2. Raise work_mem and measure again

  3. Find spills across the whole database

Official sources