Sub topic 10
The price of covering: size, writes and HOT updates
A covering index lets a query skip the table heap, but it costs disk space, write time and, in some cases, a cheaper kind of update. This chapter shows how to measure each cost so you can decide whether a covering index is worth it.
It assumes you have read the earlier chapters on index-only scans, the visibility map and the INCLUDE clause. It uses the one-million-row orders table from those chapters.
Where the cost comes from
An index with INCLUDE (total) stores a copy of total in every leaf entry. That copy has three consequences:
- Size. Each leaf entry is wider, so the index has more pages to store, cache, scan and vacuum.
- Write work. Any change to
totalnow has to change the index too. - HOT eligibility. A HOT update (heap-only tuple update) is the cheap kind of update. An indexed
totalcan disqualify it.
Measuring index size
Compare the plain index with the covering one. Both were created in earlier chapters.
SELECT c.relname,
pg_size_pretty(pg_relation_size(c.oid)) AS size,
c.relpages
FROM pg_class c
WHERE c.relname IN ('orders', 'orders_customer_idx', 'orders_customer_total_idx')
ORDER BY c.relname;The table size alone tells you little, so look at how the index compares with the table. In this schema the customer_id index holds a 4-byte integer plus a 6-byte heap pointer in each entry. The covering index adds a numeric(10,2) value, which takes a few bytes more. The covering index is therefore noticeably larger than the plain one, but still much smaller than the table. Your exact numbers depend on version and platform.
Two details affect the size:
- Only leaf pages carry the payload. Included columns are removed from the upper levels of the B-tree, which hold only the key columns needed for navigation. The extra bytes are paid in the leaf level, which is where most of the index lives anyway.
- No deduplication. Since PostgreSQL 13, a B-tree can store repeated key values once and list the heap pointers beside it. This is not available for indexes with
INCLUDEcolumns.customer_idrepeats about 100 times per value in this table, so a plain index on it benefits from deduplication and the covering index does not. The size gap is often larger than the extra column alone would suggest.
The payload also has a size limit. An index entry must fit roughly one third of a page, which is about 2.7 kB on the default 8 kB page size. Wide text values are compressed or moved out of line, but very large included columns can still make inserts fail with an index row size error. Include narrow columns.
Why size matters beyond disk
A bigger index costs more than storage:
- Cache.
shared_buffersand the OS cache hold a fixed number of pages. A larger index takes more of them, which leaves less room for the table and your other indexes. - Scan cost. An index-only scan reads leaf pages. Wider entries mean fewer entries per page, so reading all matches for a customer touches more pages.
- Maintenance.
VACUUM,REINDEXandCREATE INDEXall scale with index size.
A covering index only pays off when the read it avoids is expensive enough. If a query returns a few rows and the heap pages are already cached, the saving can be small.
Write overhead
Every INSERT adds an entry to each index. A covering index is no more expensive per insert than a plain one in terms of operations, but the entries are bigger. That means more WAL (write-ahead log) volume and more page splits, which happen when a leaf page fills up and must be divided.
DELETE is cheap at the index level: entries are not removed immediately, and VACUUM removes them later.
UPDATE is where the design matters most, and it depends on HOT.
HOT updates
PostgreSQL never overwrites a row in place. An UPDATE writes a new version of the row (a new heap tuple). Without HOT, the database must also add a new entry to every index on the table, pointing at the new version.
A HOT update avoids that. The new version stays on the same heap page, the old version is linked to it by a chain, and no index gets a new entry. Index scans follow the chain to reach the live version. It requires both of these conditions:
- No indexed column changed. The check covers every column that appears in any index on the table: key columns,
INCLUDEcolumns, columns used in a partial indexWHEREpredicate, and columns used in index expressions. - Free space on the same page for the new version.
The block above is a placeholder removed below; the real diagram follows.
The key point for covering indexes is the first question. Adding total to an index, as key or as payload, puts total in the "indexed" set. Before the index existed, UPDATE orders SET total = ... could be HOT. Afterward it cannot. The column is stored in the index, so the index must show the new value.
A non-HOT update also hurts indexes unrelated to the change. If orders has five indexes, updating total adds five new entries, not only one in the covering index.
Seeing HOT in practice
The function pg_stat_get_xact_tuples_hot_updated reports HOT updates made by the current transaction, so the result is exact and does not wait for statistics to flush. This test compares an update of the unindexed note column with an update of the included total column. Run it with orders_customer_total_idx in place.
BEGIN;
UPDATE orders SET note = 'checked' WHERE customer_id = 42;
SELECT pg_stat_get_xact_tuples_updated('orders'::regclass) AS updated,
pg_stat_get_xact_tuples_hot_updated('orders'::regclass) AS hot;
UPDATE orders SET total = total + 1 WHERE customer_id = 42;
SELECT pg_stat_get_xact_tuples_updated('orders'::regclass) AS updated,
pg_stat_get_xact_tuples_hot_updated('orders'::regclass) AS hot;
ROLLBACK;The counters accumulate within the transaction. The first query shows hot close to updated. The second shows hot unchanged, because the total updates added to updated only.
The first result may still fall short of a perfect match. The bulk load filled the pages completely, because the default fillfactor is 100. Where a page has no room for the new version, the update cannot be HOT even though no indexed column changed. This is condition 2 in practice.
For long-term monitoring, use the cumulative counters:
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 table that is updated often and shows a low hot_pct has either too many indexed columns or too little free space on its pages.
Reducing the damage
If a covering index forces a hot table off HOT updates, there are several options:
- Lower the fillfactor.
ALTER TABLE orders SET (fillfactor = 90)leaves 10% of each new page empty for HOT versions. The setting applies to pages written afterward. Existing pages change only when the table is rewritten, for example withVACUUM FULLorCLUSTER, which take heavy locks. - Include only stable columns. A column that is written once and never changes, such as
created_at, costs nothing in HOT terms. A frequently changing one, such asstatusor a runningtotal, costs the most. - Drop the INCLUDE column and accept the heap visit for queries that need it.
- Keep only the covering index you need. Drop
orders_customer_idxonceorders_customer_total_idxserves the same lookups, because the covering index can answer any query the plain one can.
An update also clears the all-visible bit on the page it touches, whether or not it is HOT. A frequently updated table therefore loses index-only benefits until the next VACUUM, as the earlier chapter showed. A covering index on a hot table pays its costs in full and gets less of its benefit.
Cost summary
| Aspect | Plain index on `customer_id` | Covering index with `INCLUDE (total)` |
|---|---|---|
| Leaf entry width | Key plus pointer | Key, payload and pointer |
| B-tree deduplication | Available | Not available |
| Upper tree levels | Key only | Key only |
| Update of `total` | HOT possible | Never HOT |
| Reads that skip the heap | No | Yes, when pages are all-visible |
Deciding whether it is worth it
Ask these questions before adding a payload column:
- How often does the query run, and how many heap pages does it touch now? Check the
Buffersline inEXPLAIN (ANALYZE, BUFFERS). - How often does the included column change? Compare
n_tup_updwith the number of queries. - How much of the table is all-visible between vacuums? A table with steady writes may show
Heap Fetchesclose to the row count. - What does the size difference look like against
shared_buffers?
A read-mostly table with a frequent, narrow lookup is the best case. A write-heavy table with a fast-changing payload column is the worst.
Exercise
The orders table has indexes on id (primary key) and customer_id only. You add CREATE INDEX ... ON orders (customer_id) INCLUDE (status). Customer support runs UPDATE orders SET status = 'shipped' WHERE id = 7 thousands of times a day, and the pages of orders have free space. Before the new index, most of these updates were HOT. What changes after the index is created, and what are two ways to reduce the impact?
Show answer
After the index exists, status is stored in an index, so changing it can no longer be a HOT update. Each such update writes a new heap version and a new entry in every index on the table, including the primary key index and the new index, and n_tup_hot_upd stops growing for these statements. To reduce the impact, you can drop the INCLUDE (status) column, accepting heap visits for the queries that wanted it, or you can lower the table's fillfactor and keep the index only if its read benefit outweighs the write cost. Keeping the payload to stable columns, such as created_at, avoids the problem entirely.