Skip to content

Instantly share code, notes, and snippets.

@CuriousLearner
Created May 10, 2025 14:22
Show Gist options
  • Save CuriousLearner/408f0e33d62cc3ec8cf893343b7001ae to your computer and use it in GitHub Desktop.
Save CuriousLearner/408f0e33d62cc3ec8cf893343b7001ae to your computer and use it in GitHub Desktop.

PostgreSQL VACUUM ANALYZE & Debug Cheatsheet

Last updated: 2025-05-10 14:16:59 UTC


βœ… Connect to a Different Database with Elevated Permissions

\c your_db your_writer_user

🧼 Run VACUUM ANALYZE on the Current DB

VACUUM ANALYZE;

⚠️ If you see permission denied, you need to connect as a user with elevated rights.


πŸ” Check Tables Not Yet Vacuumed/Analyzed

SELECT
  current_database() AS db,
  COUNT(*) FILTER (
    WHERE last_vacuum IS NULL OR last_analyze IS NULL
  ) AS tables_not_vacuumed,
  COUNT(*) AS total_tables
FROM
  pg_stat_user_tables;

πŸ“‹ See Last Vacuum and Analyze Timestamps

SELECT relname, last_vacuum, last_analyze
FROM pg_stat_user_tables
ORDER BY last_analyze DESC;

πŸ”§ Check Autovacuum Settings

SHOW autovacuum;
SHOW autovacuum_vacuum_threshold;
SHOW autovacuum_analyze_threshold;
SHOW autovacuum_vacuum_scale_factor;
SHOW autovacuum_analyze_scale_factor;

πŸ” Script to VACUUM Across Multiple Databases

For each database:

psql -U your_writer_user -d dbname -h writer.cluster-xyz.rds.amazonaws.com -c "VACUUM ANALYZE;"

Or interactively inside psql:

\c dbname your_writer_user
VACUUM ANALYZE;

πŸ” Optional: Setup .pgpass to Avoid Repeated Password Prompts

Create ~/.pgpass with:

your-host:5432:*:your_writer_user:yourpassword

Then:

chmod 600 ~/.pgpass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment