Create Index CONCURRENTLY

Build an index while the table stays writable with CREATE INDEX CONCURRENTLY, then clean up the INVALID leftovers a failed build can leave.

SqlResilience

Code

snippet
-- CONCURRENTLY:建索引期间表可正常读写,不持长期排斥锁
-- 代价:构建更慢、不能在事务块内运行(psql 单事务模式要先关掉)
-- 实现:两次全表扫描并等待既有事务结束,因此耗时远高于普通构建
CREATE INDEX CONCURRENTLY idx_orders_created_at
  ON orders (created_at);

-- 包进事务会直接报错:BEGIN; CREATE INDEX CONCURRENTLY ...; COMMIT;
-- 错误信息:CREATE INDEX CONCURRENTLY cannot run inside a transaction block
-- 期间 DML 可正常进行,构建只在两处等待既有事务结束

-- 并发构建失败会留下 INVALID 索引:先查出来再重建
SELECT indexrelid::regclass AS index_name, indisvalid
FROM pg_index
WHERE NOT indisvalid;

-- INVALID 索引不参与查询也无法原地修复:先 DROP 再 CONCURRENTLY 重来
DROP INDEX CONCURRENTLY IF EXISTS idx_orders_created_at;

What the code does

Several statements share this file — SELECT / CREATE, with pg_index among the objects involved.

In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects.

Applying it

The pg_index table is the working surface here.

Statements that matter

SELECT indexrelid::regclass AS index_name, indisvalid
FROM pg_index
WHERE NOT indisvalid;
CREATE INDEX CONCURRENTLY 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`.