Sub topic 12
What indexes cost
This chapter assumes you can read basic EXPLAIN output and have built the multicolumn, partial, and expression indexes from the earlier chapters. It uses the orders and users tables from the running schema. Every index you create speeds up some reads. It also adds work to every write, takes disk space, and gives the planner and VACUUM more to handle. This chapter shows where those costs come from and how to measure them.
Writes pay for every index
A table row lives in the heap, which is the main table storage. Each index is a separate structure that holds its own copy of the indexed values plus a pointer to the heap row. When you insert a row, PostgreSQL writes the heap tuple and then inserts one entry into each index whose definition applies to that row.
The cost per write grows with the number of indexes. An orders table with a primary key and four secondary indexes does five index insertions per INSERT, and each can split a B-tree page and write extra WAL (the write-ahead log, which is also what replicas replay).
Measuring insert cost
You can measure this without keeping the data by wrapping a bulk insert in a transaction that you roll back.
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
INSERT INTO orders (customer_id, status, total_cents)
SELECT (g % 1000) + 1, 'pending', 1000
FROM generate_series(1, 200000) AS g;
ROLLBACK;Run it once with only the primary key. Then create the indexes from the earlier chapters and run it again. Compare "Execution Time" and the buffer counts. The absolute numbers depend on your hardware. The point is that the second run is slower, and the gap grows with each index. Rolling back leaves dead tuples behind, so run VACUUM orders between experiments to keep them comparable.
Partial indexes reduce write cost
A partial index only receives rows that satisfy its WHERE predicate. If 2% of orders are pending, then orders_pending_created_idx receives about 2% of the inserts that a full index on created_at would. Deletes and updates also touch it only when a row enters or leaves the predicate, or changes an indexed value while matching it. The same index is also much smaller. Both properties are why a partial index is the cheapest way to speed up a query for a small, well-defined slice of rows.
Updates and heap-only tuples
PostgreSQL never changes a row in place. An UPDATE writes a new row version. Normally that new version needs a new entry in every index, even for indexes on columns you did not change.
The exception is a heap-only tuple (HOT) update. A HOT update is allowed when two conditions hold:
- No column that any index depends on has changed.
- The new row version fits on the same heap page as the old one.
When both hold, PostgreSQL skips all index writes and chains the new version to the old one inside the page. HOT updates are much cheaper, and they let page pruning clean up old versions without waiting for VACUUM.
The word "depends on" is broader than the indexed columns. These all count:
- Columns in a multicolumn index key.
- Columns referenced by an expression index. Changing
emailblocks HOT iflower(email)is indexed. - Columns referenced in a partial index predicate. Changing
statusblocks HOT if any index hasWHERE status = 'pending'. - Columns stored with
INCLUDE.
This changes how you should judge the partial index on status. The status column of an order changes often, such as from pending to paid to shipped. Once status appears in an index predicate, every status update loses the HOT optimization on that table. You then pay for new entries in all the other indexes too. Check how many of your updates are HOT:
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';If hot_pct falls after you add an index, that index changed your update cost, not only your insert cost. Lowering the table's fillfactor (for example ALTER TABLE orders SET (fillfactor = 90)) leaves free room in each page. That makes it more likely that a new version fits on the same page. It only affects pages written after the change, so it takes effect gradually unless you rewrite the table.
Storage
An index takes disk space, buffer cache, and backup volume. Size scales with the number of entries and the width of the indexed values. That has direct consequences for the designs in this tutorial:
- A multicolumn index on
(customer_id, created_at DESC)stores both values in each entry. It is wider than an index oncustomer_idalone. INCLUDE (total_cents)adds that column to every leaf entry. Covering indexes trade space for index-only scans.- An expression index stores the computed result. A
lower(email)index is about as large as an index onemail. - A partial index stores only matching rows. Its size is proportional to the slice you chose.
Index size also competes with table data for shared_buffers and the operating system cache. A big, rarely used index can push hot pages out of memory and slow unrelated queries.
List index sizes next to how often each is used:
SELECT s.indexrelname,
s.idx_scan,
pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes AS s
WHERE s.relname = 'orders'
ORDER BY pg_relation_size(s.indexrelid) DESC;idx_scan counts index scans since the statistics were last reset. A large index with idx_scan = 0 over a representative period is a removal candidate.
Before dropping an unused index
Read idx_scan carefully before you act on it.
- The counter resets when you run
pg_stat_reset()and after some crash recoveries. It also covers only the server you queried. If reads go to a replica, the primary shows zero scans for indexes that the replica uses. Check each node. - Monthly or quarterly jobs may not have run since the last reset.
- An index that enforces a
UNIQUEorPRIMARY KEYconstraint may never be scanned but still does necessary work. Do not drop it for that reason. - Dropping a used index can turn a fast query into a sequential scan. Test the change on a copy of production data first.
Maintenance costs
Updates and deletes leave dead entries in indexes until VACUUM removes them. More indexes make each vacuum pass longer, because vacuum must scan every index to remove pointers to dead heap rows. Indexes can also bloat. Pages that become sparse after many deletes are reused for future entries in the same key range, but they are not always returned to the operating system. Rebuilding with REINDEX INDEX CONCURRENTLY reclaims that space.
Indexes also add planning work. The planner considers every index on a table when it plans a query. A table with dozens of overlapping indexes adds planning time and can sometimes pick a worse plan, because several indexes look nearly equal.
Building an index is itself a cost. A plain CREATE INDEX blocks writes to the table for the duration of the build. CREATE INDEX CONCURRENTLY avoids that block, but it scans the table twice, takes longer, and cannot run inside a transaction block. If it fails, it can leave an invalid index behind. Look for it with:
SELECT indexrelid::regclass AS index_name
FROM pg_index
WHERE NOT indisvalid;Drop an invalid index and run the build again.
Cost summary by index type
| Design | Insert cost | Size | Blocks HOT updates when |
|---|---|---|---|
| Single-column B-tree | One entry per row | Smallest full index | That column changes |
| Multicolumn | One wider entry per row | Grows with each added column | Any key column changes |
| Partial | Only for rows matching the predicate | Proportional to the matching slice | A predicate or key column changes |
| Expression | One computed entry per row, plus the function call | About the size of the computed values | Any column used in the expression changes |
| With `INCLUDE` | One wider entry per row | Grows with included columns | An included column changes |
A practical rule
Add an index when a specific, frequent query needs it and EXPLAIN confirms the planner uses it. Prefer the narrowest design that serves the query, such as a partial index over a full one. Before adding an index, check whether an existing multicolumn index already covers the query through its leading columns. Review pg_stat_user_indexes periodically, and remove indexes that have no unique-constraint role and no recent scans.
Exercise
The orders table has an index orders_pending_created_idx ON orders (created_at) WHERE status = 'pending'. Your application runs UPDATE orders SET status = 'paid' WHERE id = 7 thousands of times per minute, and hot_pct for the table is close to 0. Why is that, and what would you check or change?
Show answer
status appears in the index predicate, so changing it counts as changing an indexed column. PostgreSQL cannot do a HOT update, and each status change writes new entries in all of the table's indexes that apply to the new row version. To confirm, compare n_tup_hot_upd and n_tup_upd in pg_stat_user_tables before and after dropping the partial index on a test copy. To fix it, either accept the cost if the partial index is valuable, or replace it with an alternative that does not depend on a frequently updated column. You could also lower fillfactor so other updates have room on the page. Do not expect fillfactor to restore HOT for updates that change status itself.
Exercise
A query on pg_stat_user_indexes shows orders_status_created_idx with idx_scan = 0 and a size of 400 MB. List three checks you should make before dropping it.
Show answer
First, check whether the index backs a unique or primary key constraint (for example in pg_constraint or pg_index.indisunique). Second, check the same statistics on every replica that serves reads, and confirm when the counters were last reset. Third, check whether a rare job, such as a monthly report, uses it. Then test the drop on a copy of production data and compare the plans of the important queries.