dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/postgresql/#16
Script #16
postgresql
Performanceread-onlyMin Version: 13

PostgreSQL Queries Spilling to Temp Files

Finds queries that spill to disk because work_mem is too small. Gives a clear candidate list for memory tuning and query optimization.

#temp-files#work_mem#pg_stat_statements
postgresql · sql
SELECT calls,
       pg_size_pretty(temp_blks_written * 8192) AS temp_written,
       round(mean_exec_time::numeric, 2) AS mean_ms,
       left(query, 150) AS query
FROM pg_stat_statements
WHERE temp_blks_written > 0
ORDER BY temp_blks_written DESC
LIMIT 20;
Operational Notes & Remediation Guidance

Queries spilling to disk indicate insufficient `work_mem`. Tune `work_mem` for the specific session or query.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 13).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.