Sub topic 10
Queries That Spill to Temporary Files
What a temporary spill means
Prerequisites: you should know basic SELECT, WHERE, ORDER BY, and LIMIT syntax. You should also know that PostgreSQL can use memory for sorting and joining rows.
PostgreSQL uses temporary files when an operation needs more memory than its allowed working space. A sort may spill while processing ORDER BY. A hash join or hash aggregate may spill while building a hash table. Temporary blocks are disk blocks belonging to this temporary work.
Spilling is not always a problem. A large report may need temporary space even when it is well designed. However, frequent or large spills can increase latency and disk I/O. They can also fill the filesystem that stores temporary files.
The pg_stat_statements view reports cumulative temporary block counters:
| Column | Meaning |
|---|---|
| `temp_blks_read` | Temporary blocks read by the query |
| `temp_blks_written` | Temporary blocks written by the query |
| `calls` | Number of executions included in the totals |
The counters are usually measured in 8 KiB blocks. Treat them as workload totals, not as a record of one execution.
Find queries that write temporary blocks
Start with queries that have written the most temporary blocks:
SELECT queryid,
calls,
temp_blks_written,
temp_blks_read,
left(query, 100) AS query
FROM pg_stat_statements
WHERE temp_blks_written > 0
ORDER BY temp_blks_written DESC
LIMIT 10;A query with many calls can rank highly because of a modest spill on every execution. A query with one call can rank highly because of one very large spill. Compare the total with calls before deciding what to investigate.
You can calculate an approximate average number of temporary blocks per call:
SELECT queryid,
calls,
temp_blks_written,
round(temp_blks_written::numeric / NULLIF(calls, 0), 1)
AS written_blocks_per_call,
left(query, 100) AS query
FROM pg_stat_statements
WHERE temp_blks_written > 0
ORDER BY written_blocks_per_call DESC
LIMIT 10;This ranking highlights queries that spill heavily during each execution. It does not show the largest individual execution because pg_stat_statements stores aggregates rather than per-execution history.
Connect the counters to query behavior
The counters tell you that temporary work occurred, but not exactly which plan node caused it. Use EXPLAIN with a representative set of parameter values:
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, count(*)
FROM orders
GROUP BY customer_id
ORDER BY count(*) DESC;Look for sort or hash nodes whose actual behavior indicates disk use. The plan can reveal whether the query sorted a large result, built a hash table, or processed more rows than expected.
Possible remedies include reducing rows before sorting, adding a suitable index, improving a stale table statistic, or rewriting a join or aggregation. Increasing work_mem can help when the operation is otherwise appropriate, but test it at the session or transaction level first:
BEGIN;
SET LOCAL work_mem = '64MB';
-- Run and inspect the suspect query here.
ROLLBACK;SET LOCAL limits the change to the current transaction, which makes testing safer.
Measure a defined workload window
The counters accumulate until they are reset or the statistics entry is removed. To measure a known test period, reset the view, run the workload, and query it again:
SELECT pg_stat_statements_reset();
-- Run the workload you want to measure.
-- Then execute the temporary-block query again.Resetting affects all accumulated pg_stat_statements statistics, so coordinate this action in a shared environment.
Exercise
Why can a query with many calls have more total temporary blocks than a slower query that spills only once?
Show answer
pgstatstatements adds temporary blocks across all executions, so repeated moderate spills can exceed one large spill.