brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: pg_stat_user_indexes idx_scan = 0 points at PostgreSQL indexes nobody uses

Postgresql
~/tips/tip-postgresql-pg-stat-user-indexes-unused

FROM pg_stat_user_indexes

Lists indexes with zero scans since the statistics were last reset, so you can review them for removal.

Every index slows down writes and takes disk space. An index that no query ever uses is pure cost, and PostgreSQL keeps a counter that shows which ones those are.

SELECT schemaname, relname, indexrelname, idx_scan, last_idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY relname;

idx_scan is the number of index scans initiated on that index. last_idx_scan is the time of the last scan, based on the most recent transaction stop time. Not every PostgreSQL version has that second column, so drop it from the query if you get an error. The view pg_stat_user_indexes is the same as pg_stat_all_indexes but only for indexes on user tables.

Treat the result as a list to review, not a to-do list. The counters only cover the time since the statistics were last reset. Per the docs, they are also reset after a crash or an immediate shutdown. An index for a monthly report may show zero today and still be needed next week.

Also skip indexes that enforce a unique or primary key constraint. They may never be scanned, but they do their job on every insert. When you do drop one, DROP INDEX CONCURRENTLY avoids blocking other queries.

Further reading: Cumulative statistics views

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link