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.
Code
-- 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
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.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.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.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What are the relations in play here?
- The references are `pg_index`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.