Check for unused Indexes

Check for unused Indexes

December 18, 2023·Christopher Tyler,Elizabeth Christensen

A small part from Elizabeth Christensen’s article on how to check unused indexes. I plan on using the query and automating this check.

postgres@raw_data=# select schemaname || '.' || relname as table
      ,indexrelname as index
      ,pg_size_pretty(pg_relation_size(i.indexrelid)) as index_size
      ,idx_scan as index_scans
  from pg_stat_user_indexes ui
  join pg_index i on ui.indexrelid = i.indexrelid
 where not indisunique
   and idx_scan < 50
   and pg_relation_size(relid) > 5 * 8192
order by pg_relation_size(i.indexrelid) / nullif(idx_scan, 0) desc nulls first
        ,pg_relation_size(i.indexrelid) desc;

If you are using read replicas, don’t forget to check those too before you delete unused indexes.