// SQL snippet

Find unused index candidates

Every index slows writes and eats disk. The usage statistics track how often each index is scanned; zeroes mean the optimizer never touches it. This query lists them with their size.

Main statement
PostgreSQL
同時涵蓋
SQL Server MySQL

The task

Writes on a busy table lag and the index list keeps growing. Before adding another one, check the usage counters for indexes that have never earned their keep.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
SELECT s.schemaname, s.relname AS table_name,
       s.indexrelname AS index_name,
       s.idx_scan AS scans,
       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   -- unique/PK indexes enforce rules even unscanned
ORDER BY pg_relation_size(s.indexrelid) DESC;

它的運作方式

pg_stat_user_indexes counts index scans since the statistics were last reset, so idx_scan = 0 means no query used the index in that window. The counters survive a clean restart but are wiped by crash recovery and by pg_stat_reset(), and each replica keeps its own, so an index that only serves read-replica queries looks unused on the primary. Dropping the biggest zeroes first reclaims the most space.

Variations

SQL Server

SQL Server
SELECT OBJECT_SCHEMA_NAME(i.object_id) AS schema_name,
       OBJECT_NAME(i.object_id) AS table_name,
       i.name AS index_name,
       ISNULL(us.user_seeks + us.user_scans + us.user_lookups, 0) AS uses,
       us.last_user_seek
FROM sys.indexes i
JOIN sys.tables t ON t.object_id = i.object_id
LEFT JOIN sys.dm_db_index_usage_stats us
  ON us.object_id = i.object_id AND us.index_id = i.index_id
   AND us.database_id = DB_ID()
WHERE i.index_id > 1 AND i.is_unique = 0
  AND ISNULL(us.user_seeks + us.user_scans + us.user_lookups, 0) = 0;
-- the DMV is cleared on every instance restart

MySQL

MySQL
-- built on performance_schema, so counts start at the last
-- server restart; it also lists indexes that back foreign keys
SELECT object_schema, object_name, index_name
FROM sys.schema_unused_indexes
WHERE object_schema = 'mydb';

Questions that come up

Is a zero-scan index always safe to drop?

No. Unique and primary-key indexes enforce rules even when no query reads them, MySQL needs an index on every foreign key column, and an index that only serves a quarterly report reads as unused for most of the year. Collect stats over a full business cycle and check what each index backs before dropping it.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.