Introduction
Indexes help databases find data faster. Checking index usage shows which indexes are helping and which are not.
Jump into concepts and practice - no test required
SELECT * FROM pg_stat_user_indexes WHERE schemaname = 'public';
SELECT indexrelname, idx_scan FROM pg_stat_user_indexes WHERE schemaname = 'public';
SELECT relname, indexrelname, idx_scan, idx_tup_read, idx_tup_fetch FROM pg_stat_user_indexes WHERE schemaname = 'public';
SELECT * FROM pg_stat_user_indexes WHERE idx_scan = 0;
SELECT indexrelname, idx_scan FROM pg_stat_user_indexes WHERE schemaname = 'public' ORDER BY idx_scan DESC LIMIT 5;
idx_scan column in pg_stat_user_indexes represent?pg_stat_user_indexesidx_scanidx_scan column counts how many times the index was used in scan operations, showing its usage frequency.idx_scan = index usage count [OK]pg_stat_user_indexes for a table named customers?pg_stat_user_indexesrelname, not tablename or table_name.relname = 'customers', which is correct to filter indexes for the table named 'customers'.relname to filter by table name [OK]SELECT indexrelname, idx_scan FROM pg_stat_user_indexes WHERE relname = 'orders';
orders has two indexes orders_pkey with 150 scans and orders_date_idx with 0 scans?orders_pkey has 150 scans and orders_date_idx has 0, the output must show both with correct values.SELECT indexrelname FROM pg_stat_user_indexes WHERE idx_scan = 0;
products?relname = 'products' to focus on indexes for the products table.idx_scan = 0 have never been used since last stats reset, so they are candidates for removal.