|
| 1 | +--- |
| 2 | +title: Index Optimization Queries |
| 3 | +description: Index audit queries |
| 4 | +tags: postgres, indexes, unused-indexes, duplicate-indexes, optimization |
| 5 | +--- |
| 6 | + |
| 7 | +# Index Optimization |
| 8 | + |
| 9 | +## Identify Unused Indexes |
| 10 | + |
| 11 | +Query to find unused indexes: |
| 12 | + |
| 13 | +```sql |
| 14 | +-- indexes with 0 scans (check pg_stat_reset / pg_postmaster_start_time first) |
| 15 | +SELECT |
| 16 | + s.schemaname, |
| 17 | + s.relname AS table_name, |
| 18 | + s.indexrelname AS index_name, |
| 19 | + pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size |
| 20 | + FROM pg_catalog.pg_stat_user_indexes s |
| 21 | + JOIN pg_catalog.pg_index i ON s.indexrelid = i.indexrelid |
| 22 | + WHERE s.idx_scan = 0 |
| 23 | + AND 0 <> ALL (i.indkey) -- exclude expression indexes |
| 24 | + AND NOT i.indisunique -- exclude UNIQUE indexes |
| 25 | + AND NOT EXISTS ( -- exclude constraint-backing indexes |
| 26 | + SELECT 1 FROM pg_catalog.pg_constraint c |
| 27 | + WHERE c.conindid = s.indexrelid |
| 28 | + ) |
| 29 | + ORDER BY pg_relation_size(s.indexrelid) DESC; |
| 30 | +``` |
| 31 | + |
| 32 | +## Indexes Per Table Guidelines |
| 33 | + |
| 34 | +- **< 5**: Normal |
| 35 | +- **5-10**: Monitor (Verify necessity) |
| 36 | +- **> 10**: Audit required (High write overhead) |
| 37 | + |
| 38 | +```sql |
| 39 | +SELECT relname AS table, count(*) as index_count |
| 40 | +FROM pg_stat_user_indexes |
| 41 | +GROUP BY relname |
| 42 | +ORDER BY count(*) DESC; |
| 43 | +``` |
| 44 | + |
| 45 | +## Identify Unused Indexes |
| 46 | + |
| 47 | +Indexes with identical definitions (after normalizing names) on the same table are duplicates: |
| 48 | + |
| 49 | +```sql |
| 50 | +SELECT |
| 51 | + schemaname || '.' || tablename AS table, |
| 52 | + array_agg(indexname) AS duplicate_indexes, |
| 53 | + pg_size_pretty(sum(pg_relation_size((schemaname || '.' || indexname)::regclass))) AS total_size |
| 54 | +FROM pg_indexes |
| 55 | +WHERE schemaname NOT IN ('pg_catalog', 'information_schema') |
| 56 | +GROUP BY schemaname, tablename, |
| 57 | + regexp_replace(indexdef, 'INDEX \S+ ON ', 'INDEX ON ') |
| 58 | +HAVING count(*) > 1; |
| 59 | +``` |
| 60 | + |
| 61 | +**Always confirm with a human before dropping or removing any indexes identified by the queries above.** Even indexes with 0 scans may be needed for infrequent but critical queries, and stats may have been reset recently. |
| 62 | + |
| 63 | +## Per-table Index Count Guidelines |
| 64 | + |
| 65 | +| Index Count | Recommendation | |
| 66 | +| ----------- | ------------------------------------------- | |
| 67 | +| <5 | Normal | |
| 68 | +| 5-10 | Review for unused/duplicates | |
| 69 | +| >10 | Audit required - significant write overhead | |
0 commit comments