Sub topic 10
Covering Indexes and Index-Only Scans
This chapter assumes you can read basic EXPLAIN output, know how a B-tree index finds rows, and understand the difference between a clustered index and a secondary index. Examples use PostgreSQL syntax.
The extra trip to the table
A secondary index stores the indexed column values plus a pointer to the full row. In PostgreSQL the pointer is a tuple identifier (TID) into the table, called the heap. In a clustered engine such as InnoDB, the pointer is the primary key value. Either way, a normal index scan has two steps:
- Search the index for matching entries.
- For each match, follow the pointer to the table and fetch the row.
Step 2 is often the expensive part. The matching rows can be scattered across many table pages, so each one may cost a random page read.
If the index already holds every column the query needs, step 2 is unnecessary. Such an index is a covering index for that query. The plan that uses it without touching the table is an index-only scan.
Covering depends on the query
An index is not covering in general. It covers a specific query, and only when every column the query references is available in the index. That includes columns in SELECT, WHERE, ORDER BY, and JOIN conditions.
Take the orders table from earlier chapters, with this index:
CREATE INDEX orders_customer_id_idx ON orders (customer_id);| Query | Covered by `orders_customer_id_idx`? | Reason |
|---|---|---|
| `SELECT customer_id FROM orders WHERE customer_id = 42` | Yes | Only `customer_id` is needed. |
| `SELECT count(*) FROM orders WHERE customer_id = 42` | Yes | No other column is needed. |
| `SELECT customer_id, total_cents FROM orders WHERE customer_id = 42` | No | `total_cents` is not in the index. |
| `SELECT * FROM orders WHERE customer_id = 42` | No | Needs every column. |
The third query is the common case. It filters on customer_id and returns one more column. You can cover it in two ways.
Two ways to cover a query
Add the column to the key
A composite index includes every column in its key, so it can cover queries that need only those columns:
CREATE INDEX orders_customer_total_idx
ON orders (customer_id, total_cents);This works, but total_cents becomes part of the sort order. It is stored in the upper levels of the tree and affects how entries are compared. That is useful only if you also filter or sort on it. If you only want to return it, the key is the wrong place.
Add the column with INCLUDE
PostgreSQL 11 and later (and SQL Server, and recent versions of other engines) let you attach payload columns that are stored in the index entries but not used for searching or ordering:
CREATE INDEX orders_customer_covering_idx
ON orders (customer_id) INCLUDE (total_cents);
EXPLAIN
SELECT customer_id, total_cents FROM orders WHERE customer_id = 42;Differences from putting the column in the key:
- Included columns do not affect ordering, so they cannot be used to seek or sort.
- Included columns can have types with no B-tree ordering support, because they are never compared.
- Included columns appear only in leaf entries, which keeps upper levels smaller.
- A
UNIQUEindex enforces uniqueness on the key columns only, not on included ones.
CREATE UNIQUE INDEX orders_ref_idx
ON orders (customer_id, created_at) INCLUDE (total_cents);Here the pair (customer_id, created_at) must be unique. total_cents is carried along for covering only.
Reading an index-only scan in EXPLAIN
With the covering index in place and a populated table, the plan should show Index Only Scan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total_cents FROM orders WHERE customer_id = 42;A typical result looks like this (numbers will differ):
Index Only Scan using orders_customer_covering_idx on orders
Index Cond: (customer_id = 42)
Heap Fetches: 0The line to watch is Heap Fetches. An index-only scan can still visit the table, and that count tells you how often it did.
Why PostgreSQL still visits the heap
PostgreSQL uses multiversion concurrency control (MVCC). Several versions of a row can exist at once, and each transaction sees only the versions visible to its snapshot. Index entries do not record visibility. So for each entry, the scan must know whether the row is visible to the current transaction.
PostgreSQL keeps a visibility map for each table. It marks pages where all rows are visible to every transaction. When the scan finds an entry pointing to such a page, it skips the table. If the page is not marked all-visible, it fetches the heap tuple to check, and Heap Fetches goes up.
This has practical consequences:
- Tables with heavy updates or deletes have many pages that are not all-visible, so index-only scans do many heap fetches.
VACUUMsets the visibility map bits. A freshly loaded table that has never been vacuumed may show a largeHeap Fetchescount even with a perfect covering index.- Autovacuum normally handles this. For a table you just bulk loaded, run
VACUUM (ANALYZE) orders;and test again.
Secondary indexes and the primary key
In a clustered engine, every secondary index entry already contains the primary key, so the primary key is effectively included for free. In InnoDB, an index on (customer_id) covers SELECT id FROM orders WHERE customer_id = 42 if id is the primary key. In PostgreSQL, the heap is not clustered by key, and the primary key is not stored in other indexes unless you add it.
Costs and limits
Covering is a trade, not a free improvement.
- Size. Every included or extra key column is duplicated from the table into the index. Wide columns such as long text make the index large, which means less of it fits in memory.
- Write cost. Each insert writes to every index. Each update that changes an indexed or included column must also write a new index entry, and it can prevent PostgreSQL's heap-only tuple (HOT) optimization, which avoids index updates when no indexed column changes. Including a frequently updated column such as
statusor a counter can make this expensive. - Entry size limit. A B-tree entry in PostgreSQL must fit roughly a third of a page. Very large included values will fail or be impractical.
- Fragility. The index covers only queries whose column list it contains. Adding one more column to a
SELECTsilently turns an index-only scan back into a regular index scan. - Selectivity still matters. If the query matches a large share of the table, the planner may choose a sequential scan even when a covering index exists, though an index-only scan is cheaper than a regular one, so the threshold shifts in its favor.
A reasonable rule: cover a query when it is frequent, latency-sensitive, returns a small number of columns, and those columns rarely change. Do not widen an index to rescue a rarely run report.
Common mistakes
- Using
SELECT *and expecting an index-only scan.*asks for every column, so the index must contain them all. List the columns you need. - Putting returned-only columns in the key. This makes the key larger and ties up ordering that nothing uses. Prefer
INCLUDE. - Judging by plan shape alone.
Index Only Scanwith a highHeap Fetchescount may perform no better than a regular index scan. Check the count. - Forgetting
ORDER BYandWHEREcolumns. A column used only in a filter must still be in the index for the query to be covered. - Leaving a redundant index. After adding
(customer_id) INCLUDE (total_cents), the older(customer_id)index is usually redundant. Confirm with usage statistics, then drop it to save write cost.
SELECT indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE relname = 'orders';An idx_scan of zero over a representative period suggests an index nothing reads.
Putting it together
For a query that fetches customer_id and total_cents for one customer:
- Run
EXPLAINwith the plain index and note theIndex Scanthat fetches from the heap. - Create the
INCLUDEindex. - Vacuum the table so the visibility map is current.
- Run
EXPLAIN (ANALYZE, BUFFERS)and confirmIndex Only Scanwith a lowHeap Fetches. - Compare buffer counts before and after, and drop the old index if it is redundant.
Exercise
A query SELECT customer_id, status FROM orders WHERE customer_id = 7 uses an index on (customer_id) INCLUDE (status). EXPLAIN shows Index Only Scan but Heap Fetches is very high on a table with frequent updates. Give two reasons this can happen and one action for each.
Show answer
First, the visibility map has few all-visible pages because the table is updated often, so the scan must check the heap for visibility. Run VACUUM, or tune autovacuum to run more often on this table. Second, the table was recently bulk loaded or modified and not yet vacuumed, so the map bits were never set. Run VACUUM (ANALYZE) on the table. A further point: because status changes often, including it may also block HOT updates, so consider whether covering this query is worth that write cost.
Exercise
You have an index on (customer_id, created_at). A report runs SELECT customer_id, created_at, total_cents FROM orders WHERE customer_id = 42 AND created_at >= '2026-01-01'. Which index change makes it covered, and why is INCLUDE better than adding total_cents to the key?
Show answer
Create an index on (customerid, createdat) INCLUDE (totalcents). The query needs all three columns, and the filter uses only the first two for searching. totalcents is only returned, so it belongs in INCLUDE. That keeps it out of the sort order and the upper tree levels, and avoids implying that the index can seek or sort on it.