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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What are the relations in play here?
- The references are `pg_index`, `pg_class`, `pg_namespace`, with 3 joins tying them together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.