Invalid Index Cleanup After Failed CREATE

A failed CREATE INDEX CONCURRENTLY leaves an INVALID index that still taxes writes; find it in pg_index, drop it, and rebuild.

SqlData Integrity

Code

snippet
-- CREATE INDEX CONCURRENTLY 失败不会回滚清理:
-- 留下 indisvalid=false 的索引,规划器不用它,但每次写入仍要维护它
-- 1) 找出全部失效索引
SELECT
    n.nspname AS schema_name,
    c.relname AS index_name,
    t.relname AS table_name
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_class t ON t.oid = i.indrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE NOT i.indisvalid
ORDER BY schema_name, index_name;

-- 2) 删掉失效索引(配合 CONCURRENTLY 避免阻塞写入)
DROP INDEX CONCURRENTLY IF EXISTS idx_orders_created_at;

-- 3) 重新创建
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_created_at
    ON orders (created_at);

How the snippet works

What runs here is SELECT / CREATE — pg_index, pg_class and pg_namespace are the objects involved.

Breaking the statements into their working parts: 3 JOINs combining rows across tables; a WHERE clause trimming the row set per statement; an ORDER BY that fixes the output order.

Points of care

  • 3 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.

Using it

Point it at the pg_index table.

Key statements

SELECT
    n.nspname AS schema_name,
    c.relname AS index_name,
    t.relname AS table_name
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_class t ON t.oid = i.indrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE NOT i.indisvalid
ORDER BY schema_name, index_name;
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_created_at
    ON orders (created_at);
DROP INDEX CONCURRENTLY IF EXISTS idx_orders_created_at;

Interactive Tools for This Topic

FAQ

What are the relations in play here?
The references are `pg_index`, `pg_class`, `pg_namespace`, with 3 joins tying them together.