Sub topic 13
Creating Indexes on a Live Table
This chapter assumes you know basic SQL, can read SELECT and WHERE clauses, and understand that an index speeds up some lookups by storing searchable data separately from the table. You should also know the basics of CREATE INDEX and EXPLAIN.
Adding an index improves reads, but the operation itself affects a live database. PostgreSQL provides two ways to build an index:
CREATE INDEXusually builds faster, but it takes a stronger lock on the table.CREATE INDEX CONCURRENTLYallows normal inserts, updates, and deletes while the index is built.
Why ordinary index creation can block work
A regular index build reads the table and creates the index in one operation:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);On a busy table, this can interfere with writes. The exact lock behavior depends on the phase of the build, but applications may experience blocked or delayed operations. A regular build is often suitable for a new table, a maintenance window, or a table that can tolerate brief disruption.
A concurrent build takes longer because PostgreSQL must account for changes made while it scans the table. It performs multiple phases and waits for transactions that could still see an incomplete view of the table.
CREATE INDEX CONCURRENTLY orders_status_created_idx
ON orders (status, created_at);The index becomes available only after the build completes successfully.
How a concurrent build changes deployment
CREATE INDEX CONCURRENTLY has important operational rules:
- It cannot run inside a transaction block.
- It cannot run inside a function or a transaction-wrapped migration.
- It uses more work and usually takes longer than a regular build.
- It still consumes CPU, disk bandwidth, and storage while it runs.
- It can wait for long-running transactions.
- It may leave an invalid index if the build fails.
A migration tool often wraps each migration in a transaction by default. In that case, configure this migration to run without a transaction, or run the statement separately.
You can inspect an index's validity through the system catalog:
SELECT indexrelid::regclass AS index_name,
indisvalid,
indisready
FROM pg_index
WHERE indexrelid = 'orders_status_created_idx'::regclass;An invalid index does not provide normal query-planning benefits. After investigating the failure, remove it and retry the build:
DROP INDEX CONCURRENTLY IF EXISTS orders_status_created_idx;
CREATE INDEX CONCURRENTLY orders_status_created_idx
ON orders (status, created_at);DROP INDEX CONCURRENTLY also cannot run inside a transaction block.
Monitoring and verifying the result
While a concurrent build runs, PostgreSQL reports progress in pg_stat_progress_create_index:
SELECT pid,
phase,
lockers_total,
lockers_done,
blocks_total,
blocks_done
FROM pg_stat_progress_create_index;After the build finishes, verify that the planner can use the index for its intended query:
EXPLAIN
SELECT id, created_at
FROM orders
WHERE status = 'pending'
ORDER BY created_at
LIMIT 20;An index-related plan is evidence that the index is a candidate for this query. The planner may still choose a sequential scan when the table is small or when fetching many rows is cheaper. Use EXPLAIN (ANALYZE, BUFFERS) when you need to compare the estimated plan with actual execution, but remember that ANALYZE runs the statement.
Choosing the build method
| Situation | Usually suitable choice |
|---|---|
| New or offline table | `CREATE INDEX` |
| Busy production table | `CREATE INDEX CONCURRENTLY` |
| Transactional migration that cannot be configured otherwise | Schedule a separate deployment step |
Exercise
A production migration fails because CREATE INDEX CONCURRENTLY was run inside a transaction. What should you change?
Show answer
Run that migration step outside a transaction, or schedule the concurrent index creation as a separate non-transactional deployment operation.