Find duplicate index candidates
ORM migrations and copy-paste DDL pile up redundant indexes over the years: same table, same columns, same order, different names. Only one of each pair earns its write overhead.
The task
A table's write overhead keeps creeping up with each new index, and some of them may cover identical column lists under different names. Find the exact pairs.
The snippet
Written for PostgreSQL. Versions for MySQL and SQLite are under Variations.
SELECT t.relname AS table_name,
a.relname AS index_a,
b.relname AS index_b,
pg_get_indexdef(b.oid) AS definition
FROM pg_index x1
JOIN pg_class a ON a.oid = x1.indexrelid
JOIN pg_index x2 ON x2.indrelid = x1.indrelid
AND x2.indexrelid > x1.indexrelid
AND x2.indkey::text = x1.indkey::text
AND x2.indisunique = x1.indisunique
AND COALESCE(pg_get_expr(x2.indexprs, x2.indrelid), '')
= COALESCE(pg_get_expr(x1.indexprs, x1.indrelid), '')
AND COALESCE(pg_get_expr(x2.indpred, x2.indrelid), '')
= COALESCE(pg_get_expr(x1.indpred, x1.indrelid), '')
JOIN pg_class b ON b.oid = x2.indexrelid
JOIN pg_class t ON t.oid = x1.indrelid
ORDER BY t.relname, a.relname;
Cómo funciona
Every pg_index row stores the covered column numbers in indkey; casting it to text turns it into a string such as '1 3', so two indexes match when they cover the same columns in the same order. Expression columns appear as 0 in indkey, which is why the expression and partial-index predicate are compared too; without them, indexes on lower(email) and upper(email) would pair up. The indexrelid > condition keeps each pair once. Two matches can still differ in index method or operator class, so read both definitions before dropping one.
Variations
MySQL
MySQL-- the sys schema already does this, including indexes that
-- are a left prefix of a wider one, and writes the DROP for you
SELECT table_name, redundant_index_name, redundant_index_columns,
dominant_index_name, dominant_index_columns, sql_drop_index
FROM sys.schema_redundant_indexes
WHERE table_schema = 'mydb';
SQLite
SQLite-- strip the CREATE INDEX name so identical definitions
-- sort next to each other
SELECT name, tbl_name, substr(sql, instr(sql, ' ON ')) AS definition
FROM sqlite_master
WHERE type = 'index' AND sql IS NOT NULL
ORDER BY tbl_name, definition, name;
Questions that come up
What about a 2-column index duplicating a 1-column index?
An index on (a, b) can serve queries that filter on a alone, so a separate index on (a) is usually redundant even though the column lists differ. The PostgreSQL query catches exact matches only, so check those prefix cases by hand. Keep the short index if it is unique, because it enforces a rule the wider one does not.
Keep reading
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.