Video in progress
How do you find unused indexes, and is dropping them safe?
Indexes with idx_scan = 0 in pg_stat_user_indexes are candidates. But before dropping, I exclude unique/PK indexes and check how long the statistics have been collected and whether the replicas use the index. An unused index slows down every write and takes up space.
📖 Answer
SELECT s.relname AS table_name,
s.indexrelname AS index_name,
s.idx_scan,
pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
AND NOT i.indisunique
ORDER BY pg_relation_size(s.indexrelid) DESC;
Places where it's easy to make a mistake:
- Fresh statistics. The statistics drop to zero after a crash or after
pg_stat_reset(). An index used by a report that runs once a month also lands on the list. I look at at least a month or two of statistics. - Replicas. Each server's statistics are separate. It may be 0 on the primary while reports on a replica use it every day. I check on all the servers.
- Unique indexes. Even if no query uses it, it enforces the constraint, so you can't drop it.
Dropping:
DROP INDEX CONCURRENTLY IF EXISTS orders_old_status_idx;
I keep the index definition in a migration, so it's easy to bring it back with CREATE INDEX CONCURRENTLY if needed.
I also look for redundant indexes: if you have both (customer_id) and (customer_id, created_at), the first is usually unnecessary.
Sign up to mark studied questions and save your progress.