dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/postgresql/#3
Script #3
postgresql
Maintenanceread-onlyMin Version: 9.4

PostgreSQL Dead Tuples, Bloat and Autovacuum Health Check

Shows dead tuple ratio and last vacuum/analyze times per table. Helps you find tables where autovacuum settings are not keeping up.

#vacuum#autovacuum#bloat#dead-tuples
postgresql · sql
SELECT schemaname, relname,
       n_live_tup, n_dead_tup,
       round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) AS dead_pct,
       last_vacuum, last_autovacuum, last_autoanalyze,
       pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_stat_user_tables
WHERE n_dead_tup > 10000
ORDER BY n_dead_tup DESC
LIMIT 30;
Operational Notes & Remediation Guidance

If `dead_pct` is consistently above 20%, consider lowering `autovacuum_vacuum_scale_factor` for that specific table.

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: 9.4).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.