Detect Duplicate Redundant Indexes

Self-join pg_index metadata to find indexes whose key column lists are identical on the same table, so redundant write amplification can be dropped.

SqlData Integrity

Code

snippet
-- 冗余索引检测:同一张表上关键列组合完全相同的 btree 索引
-- 范围说明:先排除表达式索引(indexprs 非空)、部分索引(indpred 非空)与失效索引
WITH index_columns AS (
    SELECT
        i.indexrelid,
        i.indrelid,
        (i.indkey::smallint[])[1:i.indnkeyatts] AS key_attnums
    FROM pg_index i
    WHERE i.indisvalid
      AND i.indexprs IS NULL
      AND i.indpred IS NULL
),
expanded AS (
    SELECT
        c.indexrelid,
        c.indrelid,
        array_agg(a.attname ORDER BY a.attnum) AS key_columns
    FROM index_columns c
    JOIN pg_attribute a
      ON a.attrelid = c.indrelid
     AND a.attnum = ANY (c.key_attnums)
    GROUP BY c.indexrelid, c.indrelid
)
SELECT
    e1.indrelid::regclass      AS table_name,
    e1.indexrelid::regclass    AS index_a,
    e2.indexrelid::regclass    AS index_b,
    e1.key_columns             AS shared_key_columns
FROM expanded e1
JOIN expanded e2
  ON e1.indrelid = e2.indrelid
 AND e1.key_columns = e2.key_columns
 AND e1.indexrelid < e2.indexrelid   -- 每对只报一次
ORDER BY table_name, index_a;

How it works

The statement is SELECT, touching pg_index, index_columns, pg_attribute and expanded.

The pieces that do the work: a CTE (WITH … AS) that names an intermediate result before the main query; 2 JOINs combining rows across tables; a WHERE clause keeping only the rows a statement needs; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Watch out for

  • The self-join reads only pg_index/pg_attribute catalog rows, so its cost tracks how many indexes exist — not the size of the application tables those indexes serve.

Applying it

Run it in the pg_index database context.

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`pg_index`, `index_columns`, `pg_attribute`, `expanded` — joined via 2 JOIN clauses.