Sub topic 13
Creating indexes on a live table
This chapter assumes you can read basic EXPLAIN output and know what a B-tree index is. It uses the orders and users tables from earlier chapters. It covers how to add an index to a table that is serving traffic, what can go wrong, and how to recover.
Why a plain CREATE INDEX is a problem
A plain CREATE INDEX takes a SHARE lock on the table. That lock allows reads but blocks INSERT, UPDATE, DELETE, and MERGE until the build finishes. On a large orders table the build can run for minutes. In that time every writer queues behind it, and application connections can pile up.
CREATE INDEX CONCURRENTLY avoids the write block. It takes a weaker lock, SHARE UPDATE EXCLUSIVE, which lets normal reads and writes continue. The cost is a slower build and more failure modes.
CREATE INDEX CONCURRENTLY orders_status_created_idx
ON orders (status, created_at);The CONCURRENTLY option works for every index form in this tutorial: multicolumn, partial, expression, and INCLUDE indexes, and it works with UNIQUE.
How a concurrent build works
A concurrent build is not one pass over the table. PostgreSQL does the following.
- It adds the index to the catalog in an "invalid" state, so that new writes start maintaining it.
- It waits for every transaction that could have started before the index was visible to finish.
- It scans the table and builds the index from a snapshot.
- It runs a second scan to add rows that changed during the first scan.
- It waits again for older transactions, then marks the index valid.
Each wait is for transactions that hold older snapshots. This is why the build time depends on more than table size.
Restrictions
- No transaction block.
CREATE INDEX CONCURRENTLYfails insideBEGIN ... COMMIT. Many migration tools wrap each migration in a transaction by default, so you must turn that off for this migration. Check your tool's documentation for the setting. - One at a time per table. Concurrent builds on the same table conflict with each other because both take
SHARE UPDATE EXCLUSIVE. Run them one after another. - Long transactions stall it. The build waits for older transactions. A forgotten
idle in transactionsession can hold the build for hours. - More I/O and CPU. Two scans and extra bookkeeping make it take roughly twice as long as a plain build, or longer under write load. It also uses more resources while it runs.
Failure leaves an invalid index
If a concurrent build fails or you cancel it, PostgreSQL does not remove the half-built index. It stays in the catalog marked invalid. Failures include a deadlock, a crash, or a uniqueness violation in a UNIQUE build.
An invalid index is never used for queries. It is still maintained on every write, so it costs you write time and space without helping. Find invalid indexes with the catalog:
SELECT c.relname AS index_name,
t.relname AS table_name
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_class t ON t.oid = i.indrelid
WHERE NOT i.indisvalid;In psql, the \d orders command also marks such an index as INVALID.
Drop the invalid index and retry. Use DROP INDEX CONCURRENTLY so the drop does not take a lock that blocks queries:
DROP INDEX CONCURRENTLY IF EXISTS orders_status_created_idx;
CREATE INDEX CONCURRENTLY orders_status_created_idx
ON orders (status, created_at);Unique partial indexes on a live table
The unique partial index from the earlier chapter can be built the same way. If existing rows already contain duplicates among active users, the build fails and leaves an invalid index. Find the duplicates first:
SELECT email, count(*)
FROM users
WHERE deleted_at IS NULL
GROUP BY email
HAVING count(*) > 1;Fix those rows, then build:
CREATE UNIQUE INDEX CONCURRENTLY users_active_email_key
ON users (email)
WHERE deleted_at IS NULL;Replacing an existing index without downtime
To change an index, such as adding a column, build the new one first and drop the old one afterward. Never drop first, because queries lose the index in between.
-- 1. Build the replacement under a new name.
CREATE INDEX CONCURRENTLY orders_customer_created_v2_idx
ON orders (customer_id, created_at DESC)
INCLUDE (total_cents);
-- 2. Confirm the planner uses it (run EXPLAIN on your real queries).
-- 3. Drop the old one.
DROP INDEX CONCURRENTLY orders_customer_created_idx;During the overlap, both indexes slow writes. Keep that window short.
PostgreSQL 12 and later also offer REINDEX INDEX CONCURRENTLY to rebuild an index in place, for example to remove bloat. It builds a new index and swaps it in, so it needs extra disk space for the duration. It does not change the definition.
Setting guards
Two session settings protect the application while you run DDL:
lock_timeoutmakes the statement fail instead of waiting indefinitely for a lock. A concurrent build still takes a brief lock at the start, and a queued lock request can block other queries behind it.statement_timeoutlimits total run time. Do not set it low for a concurrent build, because a timeout leaves an invalid index.
SET lock_timeout = '5s';
CREATE INDEX CONCURRENTLY orders_status_created_idx
ON orders (status, created_at);If the statement fails on the lock timeout, check for invalid leftovers, drop them, and retry at a quieter time.
Choosing between the two forms
| Situation | Use |
|---|---|
| Empty table, test database, or fresh migration before any traffic | Plain `CREATE INDEX`, which is faster |
| Production table that receives writes | `CREATE INDEX CONCURRENTLY` |
| Migration tool forces a transaction | Disable the transaction for that step |
| Table is small and a brief write pause is acceptable | Plain `CREATE INDEX` is simpler |
After the build
Do not assume the index helps. Confirm in three steps:
- Check
indisvalidis true with the query above. - Run
EXPLAINon the target query and look for an index scan or index-only scan on the new index. - For
INCLUDEindexes meant for index-only scans, runVACUUMon the table if needed. Index-only scans depend on the visibility map, whichVACUUMupdates.
A newly built index may not be chosen if table statistics are stale. Run ANALYZE orders; if the plan still shows a sequential scan on a query the index should serve.
Exercise
You run CREATE INDEX CONCURRENTLY orders_status_created_idx ON orders (status, created_at); and a colleague cancels it halfway. The next day, write latency on orders is slightly higher and the query that needed the index is still slow. What happened, how do you confirm it, and what do you do?
Show answer
The cancelled build left an invalid index in the catalog. PostgreSQL still updates it on every write, which explains the extra latency, but the planner never uses it, which explains the slow query. Confirm by selecting from pg_index where indisvalid is false, or by looking for INVALID in \d orders. Fix it by running DROP INDEX CONCURRENTLY orders_status_created_idx; and then running the CREATE INDEX CONCURRENTLY statement again, preferably after checking for long-running transactions that could stall the build.
Exercise
Your migration tool runs each migration inside a transaction, and CREATE INDEX CONCURRENTLY fails with an error. Why does it fail, and what is the fix?
Show answer
A concurrent build must wait for and commit across several separate transactions, so it cannot run inside a transaction block. The fix is to configure the migration tool to run that migration without a wrapping transaction, or to run the statement outside the tool, for example in psql.