Posted 06/13/2025

PostgreSQL Database Optimization and Cleanup

In PostgreSQL, the VACUUM ANALYZE command is used to optimize database performance by cleaning up dead tuples and updating statistics for query planning. Here’s a breakdown of what it does:

VACUUM:

Combined Command: VACUUM ANALYZE

Notes: Locks: VACUUM ANALYZE acquires a lock on the table, but it doesn’t block reads or writes unless you use VACUUM FULL. Autovacuum: PostgreSQL has an automatic vacuuming process (autovacuum) that runs periodically, but manual VACUUM ANALYZE can be useful for specific scenarios.

VACUUM ANALYZE;

Check Dead tuples

SELECT schemaname, relname, n_live_tup, n_dead_tup
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC;

Reindex

REINDEX rebuilds indexes to remove corruption or reduce bloat when performance degrades.

REINDEX TABLE tableName;

Check Index Sizes

SELECT
    schemaname,
    relname AS table_name,
    indexrelname AS index_name,
    pg_size_pretty(pg_relation_size(indexrelid)) AS index_size,
    idx_scan AS index_scans
FROM
    pg_stat_user_indexes
WHERE
    idx_scan = 0 -- Indexes that are not being used
    OR pg_relation_size(indexrelid) > 100000000; -- Large indexes (adjust size threshold)

Check Index Usage

SELECT indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE schemaname = '' AND tablename = '';