Sub topic 10
Write cost, size, and maintenance: CREATE INDEX CONCURRENTLY and usage statistics
An index speeds up reads and charges for it on every write, in disk space, and in upkeep. This chapter covers where those costs come from, how to measure them, how to build and rebuild indexes without blocking production traffic, and how to find indexes that are not earning their keep.
It assumes you can read EXPLAIN output and know the index types from the earlier chapters: B-tree, hash, GIN, GiST, and BRIN. It uses the orders table from the B-tree chapter.
Where the write cost comes from
An index is a separate on-disk structure that mirrors part of the table. Every change to the table has to keep each index consistent.
| Operation | What happens to indexes |
|---|---|
| `INSERT` | One new entry is added to every index on the table. |
| `DELETE` | The row is only marked dead. Index entries stay until `VACUUM` removes them. |
| `UPDATE` | PostgreSQL writes a new row version. It adds new entries to every index, unless the update is a HOT update (see below). |
A table with six indexes does about seven writes for each insert: one heap write and six index writes. These writes also go into the write-ahead log (WAL), so indexes increase replication traffic and backup size too.
HOT updates
A heap-only tuple (HOT) update is an optimization for a specific case. If an UPDATE changes no indexed column, and the new row version fits on the same heap page, PostgreSQL skips the index writes entirely. An index on a frequently updated column, such as status or last_seen_at, therefore disables this shortcut for every update to that column.
You can see how often HOT updates happen:
SELECT relname,
n_tup_upd,
n_tup_hot_upd,
round(100.0 * n_tup_hot_upd / nullif(n_tup_upd, 0), 1) AS hot_pct
FROM pg_stat_user_tables
WHERE relname = 'orders';A low hot_pct on an update-heavy table suggests that some index covers a column that changes often. Lowering the table's fillfactor leaves free space on each page, which makes HOT updates more likely.
Measuring the cost yourself
This script inserts a million rows into a table with no secondary indexes, adds three indexes, and repeats the insert. Run it in psql.
\timing on
CREATE TABLE write_test (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
a integer NOT NULL,
b integer NOT NULL,
c text NOT NULL
);
INSERT INTO write_test (a, b, c)
SELECT i % 1000, i, md5(i::text)
FROM generate_series(1, 1000000) AS i;
CREATE INDEX write_test_a_idx ON write_test (a);
CREATE INDEX write_test_b_idx ON write_test (b);
CREATE INDEX write_test_c_idx ON write_test (c);
INSERT INTO write_test (a, b, c)
SELECT i % 1000, i, md5(i::text)
FROM generate_series(1, 1000000) AS i;The second insert is typically several times slower than the first. The exact ratio depends on your hardware, your settings, and the randomness of the indexed values. The md5 column is the worst case because every new key lands on a random leaf page.
Index size
Index size matters for three reasons. Large indexes compete with table data for shared_buffers and the operating system cache. They slow VACUUM. They also lengthen backups and replica rebuilds.
pg_indexes_size reports the total for one table, and pg_relation_size reports a single index:
SELECT pg_size_pretty(pg_table_size('orders')) AS table_size,
pg_size_pretty(pg_indexes_size('orders')) AS all_indexes_size;
SELECT indexrelname,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname = 'orders'
ORDER BY pg_relation_size(indexrelid) DESC;Sizes vary a lot by type. A BRIN index on a billion-row table can be a few hundred kilobytes, since it stores one summary per block range. A B-tree on the same column holds one entry per row and can reach tens of gigabytes. A GIN index on jsonb can be larger than the table it indexes. A partial index only holds rows matching its WHERE clause, so it is often a small fraction of the full-column version.
Bloat
Indexes can grow beyond what their live entries need. After heavy deletes or updates, B-tree pages may be mostly empty. VACUUM removes dead entries and recycles fully empty pages for reuse, but it does not shrink the file or merge half-empty pages. If the table later receives keys in a different range than the ones deleted, the empty space is never filled.
The pgstattuple extension measures this:
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT index_size, avg_leaf_density, leaf_fragmentation
FROM pgstatindex('orders_customer_created_idx');A fresh B-tree has an avg_leaf_density near 90, which is the default fillfactor. A value well below 50 on a large index suggests a rebuild would reclaim space.
Some types have their own maintenance behavior:
- GIN buffers new entries in a pending list for fast writes (the
fastupdateoption). The list is merged into the main structure byVACUUMor when it exceedsgin_pending_list_limit. A query that finds a long pending list has to scan it linearly, which can cause occasional slow queries. - BRIN only summarizes a block range once it is full. Newly appended ranges stay unsummarized, and every query must scan them, until autovacuum summarizes them or you call
brin_summarize_new_values('index_name'). Creating the index withWITH (autosummarize = on)asks PostgreSQL to summarize these ranges as soon as they fill. - Index-only scans depend on the visibility map, which
VACUUMmaintains. A table that is rarely vacuumed loses the benefit ofINCLUDEcolumns, because the executor must still visit the heap to check row visibility.
Building indexes without blocking writes
A plain CREATE INDEX takes a SHARE lock on the table. Reads continue, but every INSERT, UPDATE, and DELETE waits until the build finishes. On a large, busy table that can mean minutes or hours of stalled writes.
CREATE INDEX CONCURRENTLY avoids this by building the index while writes continue:
CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);It takes a weaker lock, SHARE UPDATE EXCLUSIVE, which allows normal reads and writes. To stay correct while rows change, it scans the table twice and waits for older transactions to finish between phases. The trade-offs are:
- It takes roughly twice as long as a plain build and does more total work.
- It cannot run inside a transaction block. A migration tool that wraps every migration in a transaction will fail with an error, and you must configure it to run this statement outside one.
- A long-running open transaction, including one that is idle, makes the build wait for it. A build that seems stuck is often waiting on such a transaction. Look for it in
pg_stat_activity. - It works for every index type covered in this tutorial, and for unique indexes.
Invalid indexes
If a concurrent build fails, for example from a deadlock, a cancelled statement, or a duplicate value in a unique index, PostgreSQL does not remove the half-built index. It stays in the catalog marked invalid. The planner ignores it, but it is still updated on every write, so it costs you and gives nothing back.
Find invalid indexes with:
SELECT n.nspname AS schema_name,
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
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE NOT i.indisvalid;Drop the leftover and retry:
DROP INDEX CONCURRENTLY IF EXISTS orders_status_idx;
CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);DROP INDEX normally takes an ACCESS EXCLUSIVE lock, which blocks even reads. The CONCURRENTLY form avoids that. It also cannot run in a transaction block, and it cannot drop an index that backs a constraint.
Rebuilding and replacing
REINDEX INDEX CONCURRENTLY (PostgreSQL 12 and later) rebuilds a bloated index without blocking writes. It builds a new copy next to the old one and swaps them:
REINDEX INDEX CONCURRENTLY orders_customer_created_idx;To change an index definition, build the new one first, then drop the old one:
CREATE INDEX CONCURRENTLY orders_customer_created_v2_idx
ON orders (customer_id, created_at DESC)
INCLUDE (total);
DROP INDEX CONCURRENTLY orders_customer_created_idx;Dropping first would leave queries without an index while the new one builds.
Finding indexes you do not use
pg_stat_user_indexes records usage for every index. The useful columns are:
| Column | Meaning |
|---|---|
| `idx_scan` | Number of index scans started on this index. |
| `idx_tup_read` | Index entries returned by scans. |
| `idx_tup_fetch` | Live table rows fetched by simple index scans. |
PostgreSQL 16 and later also provide last_idx_scan, the time of the most recent scan.
This query lists candidates for removal, largest first:
SELECT s.schemaname,
s.relname,
s.indexrelname,
s.idx_scan,
pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
AND NOT i.indisunique
ORDER BY pg_relation_size(s.indexrelid) DESC;The NOT i.indisunique filter matters. Primary key and unique indexes enforce constraints even if no query ever reads them, and so do exclusion constraints. A zero scan count does not make those safe to drop.
Limits of the statistics
Zero scans is evidence, not proof. Check these before dropping anything:
- Counters reset. Statistics are cleared by
pg_stat_reset()and by a crash recovery. Check the reset time withSELECT stats_reset FROM pg_stat_database WHERE datname = current_database();. An index with zero scans over two days tells you little. A monthly report may be the only query that uses it. - Replicas have their own statistics. Counters are per server. An index unused on the primary may serve all queries on a read replica. Check every node that receives reads.
- Index scans are counted, not planner value. An index may keep a query plan fast simply by existing. For example, a foreign key column index helps cascading deletes on the parent table, and those show up as scans only when they run.
- Overlap hides redundancy. An index on
(customer_id)is usually redundant if(customer_id, created_at)exists, since the multicolumn index serves the same equality lookups. The statistics will not tell you this. Compare definitions withpg_indexes.
A cautious sequence for removing an index is to note its definition, observe a full business cycle, drop it with DROP INDEX CONCURRENTLY, and keep the CREATE INDEX statement ready to restore it.
Practical guidelines
- Add indexes for measured queries, and confirm with
EXPLAIN (ANALYZE, BUFFERS)that the planner uses them. - Prefer partial indexes and narrow indexes to reduce write cost and size.
- Always use
CONCURRENTLYfor create, drop, and reindex on tables serving live traffic. Keep a check for invalid indexes after migrations. - Review index sizes and usage on a schedule, not only when something is slow.
- For bulk loads into an empty table, load the data first and create indexes afterward. One sorted build is much faster than many incremental insertions.
Exercise
A migration ran CREATE INDEX CONCURRENTLY orders_total_idx ON orders (total); and failed with a deadlock error. A week later, writes to orders are slightly slower than before the migration, and EXPLAIN never shows orders_total_idx. What is the likely cause, how do you confirm it, and how do you fix it?
Show answer
The failed concurrent build left an invalid index. The planner ignores it, but PostgreSQL still updates it on every write, which adds cost. Confirm with a query on pg_index where indisvalid is false (joined to pg_class to get the index name). Fix it with DROP INDEX CONCURRENTLY orders_total_idx; and then run the CREATE INDEX CONCURRENTLY statement again, outside a transaction block.
Exercise
pg_stat_user_indexes shows idx_scan = 0 for orders_pkey and for orders_old_status_idx, which is a plain non-unique index. Which one can be considered for removal, and what two things should you check first?
Show answer
Only orders_old_status_idx is a candidate. orders_pkey backs the primary key constraint, so it is needed even if no query scans it. Before dropping the other index, check when statistics were last reset (pg_stat_database.stats_reset) so the zero covers a long enough period, and check the same statistics on every read replica, because a replica may use the index.
Exercise
Why does CREATE INDEX CONCURRENTLY fail inside BEGIN; ... COMMIT;, and what is the practical consequence for schema migration tools?
Show answer
It must wait for other transactions between its scan phases and commit its own work in separate steps, which cannot happen inside one enclosing transaction, so PostgreSQL rejects it. Migration tools that wrap each migration in a transaction must be configured to run this statement outside a transaction, usually in a separate migration step.