The symptom
Sorts, hash joins and hash aggregates need working memory in proportion to the rows they handle. Each engine caps that memory. When an operation needs more than its cap, it does not fail: it writes part of its data to temporary files and works through them in passes. The query still returns the right answer, only slower, and it now depends on the speed of the temp disk.
There are two causes, with different fixes. Either the cap is too small for an honest workload, or the engine expected far fewer rows than arrived and reserved too little. The query plan viewer reports spills with the amount written to disk. The examples use a shop schema with 400,000 orders and 800,000 order items.
Diagnose it
PostgreSQL: Sort Method and Batches
A sort that stayed in memory reports quicksort con Memory. One that spilled reports external merge con Disk. With BUFFERS, the temp file traffic shows up as temp read y written:
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF)
SELECT * FROM orders ORDER BY total;
Sort (cost=56638.78..57638.78 rows=400000 width=37) (actual rows=400000.00 loops=1)
Sort Key: total
Sort Method: external merge Disk: 19120kB
Buffers: shared hit=4485, temp read=2390 written=2397
A hash join that did not fit splits its input into batches and processes them one at a time. Batches: 1 means it fit; anything higher went to disk:
SET max_parallel_workers_per_gather = 0;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF)
SELECT o.customer_id, count(*)
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
GROUP BY o.customer_id;
-> Hash Join (cost=15045.00..38054.02 rows=800000 width=4) (actual rows=800000.00 loops=1)
Buckets: 262144 Batches: 4 Memory Usage: 5954kB
Buffers: shared hit=4482, temp written=1024
A hash aggregate reports Disk Usage the same way:
EXPLAIN (ANALYZE, BUFFERS OFF, TIMING OFF, SUMMARY OFF)
SELECT product_id, order_id, count(*)
FROM order_items
GROUP BY product_id, order_id;
HashAggregate (cost=60096.00..69843.73 rows=349773 width=16) (actual rows=800000.00 loops=1)
Planned Partitions: 4 Batches: 21 Memory Usage: 8505kB Disk Usage: 19928kB
That plan also shows the other cause: the planner expected about 350,000 groups and got 800,000. To find spills across the whole server, log_temp_files writes every temp file above a size to the log, and the temp spilling snippet reads the totals per database.
Lossy bitmap heap scans
A bitmap scan has the same limit. The bitmap normally records each matching row. When it outgrows work_mem it degrades to recording only which pages contain matches, and the scan must then re-test every row on those pages. The plan reports those pages as lossy:
CREATE INDEX orders_customer_idx ON orders (customer_id);
SET work_mem = '64kB';
EXPLAIN (ANALYZE, BUFFERS OFF, TIMING OFF, SUMMARY OFF)
SELECT sum(total) FROM orders WHERE customer_id BETWEEN 2 AND 600;
RESET work_mem;
-> Bitmap Heap Scan on orders (cost=147.76..9962.29 rows=10472 width=6) (actual rows=10800.00 loops=1)
Recheck Cond: ((customer_id >= 2) AND (customer_id <= 600))
Rows Removed by Index Recheck: 90318
Heap Blocks: exact=551 lossy=1045
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..145.14 rows=10472 width=0) (actual rows=10800.00 loops=1)
Nothing is written to disk here; the cost is the extra rows read and rechecked. A few lossy pages are harmless. When most pages are lossy the fix is the same as for a spill: more work_mem for that query.
SQL Server: spill warnings and the memory grant
SQL Server decides how much memory a query gets before it starts, from the estimated row counts. That reservation is the memory grant. If more rows arrive than estimated, the sort or hash spills to tempdb, and the actual plan carries a warning on the operator. A procedure compiled for a small customer and run for a large one shows it:
CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);
GO
CREATE OR ALTER PROCEDURE dbo.CustomerOrdersByTotal @CustomerId int
AS
SELECT OrderId, Total, Reference, OrderDate
FROM dbo.Orders WHERE CustomerId = @CustomerId
ORDER BY Total DESC;
GO
SET NOCOUNT ON;
GO
EXEC dbo.CustomerOrdersByTotal @CustomerId = 4242;
GO
SET STATISTICS XML ON;
GO
EXEC dbo.CustomerOrdersByTotal @CustomerId = 1;
GO
SET STATISTICS XML OFF;
<SpillToTempDb SpillLevel="1" SpilledThreadCount="1" />
<SortSpillDetails GrantedMemoryKb="1024" UsedMemoryKb="1024" WritesToTempDb="171" ReadsFromTempDb="171" />
The sort was granted 1,024 KB because the plan expected 20 rows, and 40,000 arrived. Management Studio draws this as a yellow warning triangle on the Sort operator. The grant for the whole query is on the root operator under MemoryGrantInfo, where GrantedMemory y MaxUsedMemory show what was reserved and what was used.
The opposite problem has the same root. When the estimate is far too high, the query reserves memory it never touches, and other queries wait for memory that is sitting idle. Queries currently holding or waiting for a grant are listed in a view:
SELECT session_id, requested_memory_kb, granted_memory_kb, used_memory_kb, wait_time_ms
FROM sys.dm_exec_query_memory_grants
ORDER BY requested_memory_kb DESC;
La session memory grants snippet adds the query text.
MySQL: Sort_merge_passes
MySQL sorts in a buffer of sort_buffer_size bytes per session. A sort that does not fit is written out in chunks that are merged afterwards, and each merge is counted in a status variable:
SET SESSION sort_buffer_size = 32768;
FLUSH STATUS;
SELECT COUNT(*) FROM (
SELECT order_id, total FROM orders ORDER BY total, reference LIMIT 400000
) AS sorted;
SHOW SESSION STATUS LIKE 'Sort_merge_passes';
| Sort_merge_passes | 97 |
The server-wide counter (SHOW GLOBAL STATUS LIKE 'Sort_merge_passes') tells you whether sorts spill in normal operation. A value that keeps climbing means they do.
Fix it
Fix the row estimate first
If the plan expected far fewer rows than it got, more memory is the wrong fix: the engine will under-reserve again on the next query. Go to the operator where estimated and actual rows part ways and fix that, as described under row estimate mismatch. In the SQL Server example the cause is a plan compiled for a different parameter value, which is parameter sniffing.
Give the operation less to do
Memory use follows rows times row width. Select only the columns you need instead of *, filter before the sort or join, and check whether an index can deliver the order so that no sort is needed at all (see expensive sorts).
PostgreSQL: raise work_mem for the query
work_mem is the cap for each sort or hash operation, not for the query or the server: one query can use it several times over, and every connection can do so at once. Raise it for the session or transaction that needs it and leave the server default modest:
SET work_mem = '64MB';
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF)
SELECT * FROM orders ORDER BY total;
RESET work_mem;
Sort (cost=45701.28..46701.28 rows=400000 width=37) (actual rows=400000.00 loops=1)
Sort Key: total
Sort Method: quicksort Memory: 34257kB
Buffers: shared hit=4482
Hash operations get work_mem multiplied by hash_mem_multiplier. Note that the in-memory sort used more memory than the on-disk one used disk; the two formats differ, so size work_mem desde la Memory figure of a run that fit, not from the Disk figure.
MySQL: raise sort_buffer_size for the session
SET SESSION sort_buffer_size = 64 * 1024 * 1024;
FLUSH STATUS;
SELECT COUNT(*) FROM (
SELECT order_id, total FROM orders ORDER BY total, reference LIMIT 400000
) AS sorted;
SHOW SESSION STATUS LIKE 'Sort_merge_passes';
| Sort_merge_passes | 0 |
As with PostgreSQL, set it per session for the queries that need it. sort_buffer_size is allocated per sort, so a large global value multiplies across connections.
SQL Server: correct the grant
Once the estimate is right the grant follows. Where it cannot be fixed, OPTION (RECOMPILE) gives each call a grant sized for its own values:
CREATE OR ALTER PROCEDURE dbo.CustomerOrdersByTotal @CustomerId int
AS
SELECT OrderId, Total, Reference, OrderDate
FROM dbo.Orders WHERE CustomerId = @CustomerId
ORDER BY Total DESC
OPTION (RECOMPILE);
GO
SET NOCOUNT ON;
SET STATISTICS XML ON;
GO
EXEC dbo.CustomerOrdersByTotal @CustomerId = 1;
On our test server this run had no spill warning. For a query that reserves far more than it uses, the MAX_GRANT_PERCENT query hint caps the grant.
When to leave it alone
A spill of a few megabytes on a query that runs once a night is not worth a setting change. Large sorts for reports and index builds are expected to use disk. Act when the spill is on a frequent query, when temp reads make up much of its run time, or when the cause is a wrong estimate that is also distorting the rest of the plan.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Look for external merge, Batches above 1 or Disk Usage (PostgreSQL), a spill warning (SQL Server), or Sort_merge_passes (MySQL).
- Compare estimated and actual rows on the spilling operator.
- If the estimate is wrong, fix the estimate before touching memory settings.
- Trim the columns and rows that reach the sort or hash.
- Raise work_mem or sort_buffer_size for the session that runs the query, not for the server.
- Capture the plan again and confirm the operation now runs in memory.
Questions that come up
What does external merge Disk mean in PostgreSQL?
The sort needed more than work_mem, so PostgreSQL wrote sorted runs to temporary files and merged them. The Disk figure is the temp space used. The same sort with enough work_mem reports quicksort and a Memory figure instead.
What does Batches mean on a Hash node?
It is the number of pieces the hash join split its input into. Batches: 1 means the whole hash table fit in memory. A higher number means the join wrote the other batches to temp files and processed them one after another.
How much work_mem should I set?
Enough for the operation that spills, set for the session or transaction that runs it. The limit applies per sort or hash node, and every connection can use it at the same time, so a high server-wide value can exhaust memory under load.
What is a memory grant in SQL Server?
It is the memory reserved for a query's sorts and hashes before it starts, sized from the estimated row counts. Too small and the query spills to tempdb. Too large and the memory is held unused while other queries wait for their own grants.
What are lossy heap blocks?
They are pages a PostgreSQL bitmap scan could only remember as a whole, because the bitmap would not fit in work_mem with one bit per row. Every row on a lossy page is read and re-tested against the condition, which shows as Rows Removed by Index Recheck.