CREATE INDEX
CREATE INDEX takes a SHARE lock which blocks all writes for the duration of the index build. Use CONCURRENTLY to allow writes during the build.
The Problem
sql
-- SHARE lock, blocks all writes while index is built
CREATE INDEX idx_users_email ON users(email); Safe Rewrite
sql
SET lock_timeout = '2s';
-- CONCURRENTLY: no lock on writes, index built in background
-- Must run OUTSIDE a transaction block
-- DROP first: a failed earlier build leaves an INVALID index that
-- IF NOT EXISTS would silently skip. Both statements run outside a transaction.
DROP INDEX CONCURRENTLY IF EXISTS idx_users_email;
CREATE INDEX CONCURRENTLY idx_users_email ON users(email); Do not write CREATE INDEX CONCURRENTLY IF NOT EXISTS as the idempotent form. If a previous concurrent build failed, PostgreSQL checks only the index name, skips the statement, and leaves the INVALID index in place with no usable index behind it. The DROP INDEX CONCURRENTLY IF EXISTS first clears any leftover (it also drops a valid index of the same name, which the next statement rebuilds). To keep a valid index instead, check pg_index.indisvalid before deciding.
Important:
CREATE INDEX CONCURRENTLY cannot run inside a transaction. pgfence will flag it as an error if it detects it inside a BEGIN/COMMIT block.