How do you create an index on a large PostgreSQL table without blocking writes?

IntermediateConceptPostgreSQL
Answer

Short answer

Use CREATE INDEX CONCURRENTLY. A normal CREATE INDEX blocks writes to the table until it finishes, which can mean minutes of outage on a big table. CONCURRENTLY builds the index while inserts, updates and deletes continue — it's slower and can't run inside a transaction block.

Example

CREATE INDEX CONCURRENTLY idx_orders_customer_id ON orders (customer_id);
DROP INDEX CONCURRENTLY idx_orders_old;
REINDEX INDEX CONCURRENTLY idx_orders_customer_id;     -- PG 12+

Gotchas

  • If it fails (e.g. a duplicate in a unique index), it leaves an INVALID index — find and drop it:
    SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;
    
  • Migration tools wrap statements in transactions by default — mark these migrations as non-transactional (Flyway: separate script; Alembic: autocommit_block; Django: atomic = False).

What to say in the interview

"CREATE INDEX CONCURRENTLY builds the index without blocking writes, at the cost of time and not being allowed in a transaction. If it fails it leaves an invalid index to drop, and migrations must run it outside a transaction."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: PostgreSQL basics

More on PostgreSQL