Part 17 / Topic 8 of 8
CREATE INDEX CONCURRENTLY
Plain CREATE INDEX takes a lock that blocks writes for the whole build — minutes of frozen production on a big table. The online version builds in phases, letting writes continue:
BEGIN;
CREATE INDEX CONCURRENTLY idx_users_oops ON big_users (joined_on);
ROLLBACK;
BEGIN
ERROR: CREATE INDEX CONCURRENTLY cannot run inside a transaction block
ROLLBACK
That error is the fine print announcing itself: CONCURRENTLY manages its own transactions (multiple scans, waiting out concurrent writers), so it cannot run inside yours — a migration-tool gotcha everyone hits once. The other clause of the contract: if the build fails midway it leaves an INVALID index (visible in \d, maintained but unused) — drop it and retry. The production rule is simply: on a big live table, build with CONCURRENTLY, run it on its own, and keep a retry plan. Same applies to DROP INDEX CONCURRENTLY and — via REINDEX CONCURRENTLY — to rebuilding bloated indexes in place.
🧪 Quick quiz — answer from memory, then check.
- What does plain CREATE INDEX block, and for how long?
- Two quirks of CONCURRENTLY?
Show the answers
- All writes to the table, for the entire build.
- It refuses to run inside a transaction block, and a failed build leaves an INVALID index to drop and retry.
Done here? The practice set for Part 17 — 5 exercises with solutions — is on the part page.