// SQL snippet

Find queries spilling to temp in PostgreSQL

When a sort or hash does not fit in work_mem, PostgreSQL spills to disk. This finds the queries doing it most.

Main statement
PostgreSQL
Also covers
SQL Server MySQL

The task

Each sort, hash join and hash aggregate in a plan gets up to work_mem of memory (hash operations get work_mem times hash_mem_multiplier, 2.0 by default). When the data does not fit, PostgreSQL writes it to temporary files and merges or re-reads them, which is much slower than doing the work in memory. pg_stat_statements accumulates temp_blks_written per normalized query, so the queries that spill most often and most heavily are easy to rank. It needs the extension installed and listed in shared_preload_libraries.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
SELECT calls,
       temp_blks_written,
       ROUND(temp_blks_written::numeric / 128, 1) AS temp_mb_written,
       ROUND(temp_blks_written::numeric / NULLIF(calls, 0) / 128, 2) AS temp_mb_per_call,
       ROUND(mean_exec_time::numeric, 2) AS mean_ms,
       LEFT(query, 120) AS query
FROM pg_stat_statements
WHERE temp_blks_written > 0
ORDER BY temp_blks_written DESC
LIMIT 20;

How it works

temp_blks_written counts 8 KB blocks written to temp files, so dividing by 128 gives megabytes (8192 bytes per block, 128 blocks per MB). temp_mb_per_call is the more useful number. A few MB per call on a query that runs a million times means a modest work_mem increase, for that role or session, removes a large total cost. Gigabytes per call usually means the query sorts or hashes far more rows than it needs, for example a DISTINCT or GROUP BY over a join that multiplied rows, and the query needs rewriting. EXPLAIN (ANALYZE) shows which node spilled: Sort Method: external merge Disk, or Batches greater than 1 on a Hash node.

Variations

MySQL: statements creating on-disk temp tables

MySQL
SELECT COUNT_STAR,
       SUM_CREATED_TMP_TABLES, SUM_CREATED_TMP_DISK_TABLES,
       ROUND(SUM_TIMER_WAIT / 1e12, 3) AS total_sec,
       LEFT(DIGEST_TEXT, 120) AS digest
FROM performance_schema.events_statements_summary_by_digest
WHERE SUM_CREATED_TMP_DISK_TABLES > 0
ORDER BY SUM_CREATED_TMP_DISK_TABLES DESC
LIMIT 20;

SQL Server: running requests spilling into tempdb

SQL Server
SELECT tu.session_id, r.command, r.status,
       SUM(tu.internal_objects_alloc_page_count - tu.internal_objects_dealloc_page_count) / 128 AS internal_mb,
       SUM(tu.user_objects_alloc_page_count - tu.user_objects_dealloc_page_count) / 128 AS user_obj_mb
FROM sys.dm_db_task_space_usage tu
JOIN sys.dm_exec_requests r ON r.session_id = tu.session_id AND r.request_id = tu.request_id
GROUP BY tu.session_id, r.command, r.status
HAVING SUM(tu.internal_objects_alloc_page_count) > 0
ORDER BY internal_mb DESC;

Questions that come up

Should I just raise work_mem globally?

Not without arithmetic. work_mem applies per sort or hash node, not per query, and one complex query can have several such nodes, each in every parallel worker. A 64 MB work_mem with 200 concurrent sorts can claim about 12.5 GB, and hash nodes can take twice that. Raise it for the role or session that runs the heavy reports (ALTER ROLE reporting SET work_mem = '256MB'), and keep the global value modest.

The top query is a simple ORDER BY on an indexed column. Why does it spill?

An index on the sort column only avoids the sort if the planner reads rows through that index. If the WHERE clause is served by a different index, or the query sorts the output of a join or aggregate, PostgreSQL sorts explicitly. Run EXPLAIN (ANALYZE) and look for Sort Method: external merge Disk. An index that covers the filter columns first and the sort column after them, such as (status, created_at) for WHERE status = $1 ORDER BY created_at, removes the sort.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.