Sub topic 11
Covering queries with INCLUDE
This chapter assumes you can read basic EXPLAIN output and that you know how a multicolumn B-tree index is searched. It uses the orders and users tables from earlier chapters. The goal is to answer a query from the index alone, so PostgreSQL never has to visit the table.
Why the table visit costs something
A normal index scan finds matching entries in the index, then follows a pointer to each row in the table (the heap) to read the columns the query asked for. Each pointer can mean a random read of a different heap page. For a query that returns many rows, those heap visits are often most of the cost.
An index-only scan skips the visit when every column the query needs is already stored in the index. The index entry holds the answer, so PostgreSQL reads only index pages.
Take this query:
SELECT customer_id, total_cents
FROM orders
WHERE customer_id = 42;It filters on customer_id and returns customer_id and total_cents. An index on (customer_id) can find the rows, but total_cents lives only in the heap. You have two ways to put it in the index.
Two ways to add a column
The first way is to make it part of the key:
CREATE INDEX orders_customer_total_idx
ON orders (customer_id, total_cents);This works, but it changes what the index is. Every column in the key takes part in ordering, and the index can be searched on it. If you only want to carry total_cents along, that is more than you need. In a unique index, a key column also becomes part of the uniqueness rule.
The second way is INCLUDE:
CREATE INDEX orders_customer_cover_idx
ON orders (customer_id)
INCLUDE (total_cents);Here customer_id is the only key column. total_cents is a payload column. It is stored in the index entries, but it is not part of the sort order and the index cannot be searched by it. INCLUDE for B-tree indexes is available from PostgreSQL 11.
| Property | Key column | `INCLUDE` column |
|---|---|---|
| Part of the sort order | Yes | No |
| Can be used to search the index | Yes | No |
| Counts toward uniqueness | Yes, in a unique index | No |
| Can be returned by an index-only scan | Yes | Yes |
| Needs an ordering operator for its type | Yes | No |
The last row matters in practice. A key column needs a B-tree operator class, so its type must be sortable. An included column can have any type, including types with no ordering, because the index never compares it.
Checking the plan
Run EXPLAIN on the query:
EXPLAIN
SELECT customer_id, total_cents
FROM orders
WHERE customer_id = 42;When the planner picks the covering index, the plan contains a node like this:
Index Only Scan using orders_customer_cover_idx on orders
Index Cond: (customer_id = 42)If you instead see Index Scan, Bitmap Heap Scan, or Seq Scan, the planner chose another route. On a small or freshly loaded table, a sequential scan is often cheaper, so a missing index-only scan is not always a bug. To test whether the index can serve the query, disable sequential scans for your session and look again:
SET enable_seqscan = off;
EXPLAIN SELECT customer_id, total_cents FROM orders WHERE customer_id = 42;
RESET enable_seqscan;Use that setting only to experiment. It is not a fix for production queries.
The visibility map and heap fetches
"Index-only" has a catch. PostgreSQL uses multiversion concurrency control (MVCC), so several versions of a row can exist at once. Each transaction sees only the versions visible to it. The index does not store visibility information, so by default only the heap can say whether an index entry is visible to your transaction.
To avoid the heap visit, PostgreSQL consults the visibility map. This is a small per-table structure that marks heap pages where every row is visible to all transactions. For an index entry that points into an all-visible page, the heap visit is skipped. For any other entry, PostgreSQL must still fetch the heap page.
EXPLAIN (ANALYZE) reports how often that happened:
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total_cents
FROM orders
WHERE customer_id = 42;Index Only Scan using orders_customer_cover_idx on orders
Index Cond: (customer_id = 42)
Heap Fetches: 0The numbers vary, but the shape is the point. Heap Fetches: 0 means the scan never touched the table. A large count means the visibility map is out of date for those pages, and the "index-only" scan is doing nearly as much work as a plain index scan.
Vacuum maintains the visibility map. After heavy updates or deletes, pages are not marked all-visible until a vacuum runs, either autovacuum or a manual one:
VACUUM (ANALYZE) orders;A table that is written to constantly may never have many all-visible pages. Covering indexes pay off most on tables that are read much more often than they are modified, or where the hot pages are mostly stable.
Rules the query must meet
An index-only scan is possible only when the index contains every column the query references, not just the ones in the select list. That includes columns in WHERE, ORDER BY, and JOIN conditions.
SELECT *almost never qualifies, because it asks for every column of the table.- Adding a column such as
statusto the select list of the example query breaks the covering. The planner falls back to visiting the heap, unlessstatusis also in the index. - A condition on an included column can still be checked against the index entry. The index cannot use that column to navigate the tree, so the condition acts as a filter on the entries it reads.
Because the covering depends on the query text, tune the index to a specific, frequent query. If you add columns until many queries are covered, the index grows toward a copy of the table.
Combining INCLUDE with other index features
INCLUDE works alongside the features from earlier chapters.
A unique index can carry payload columns without widening the uniqueness rule:
CREATE UNIQUE INDEX users_email_cover_key
ON users (email)
INCLUDE (id);Uniqueness applies to email alone. A lookup such as SELECT id FROM users WHERE email = '[email protected]' can then be answered from the index. If you had made (email, id) the key instead, any two rows with the same email would still be rejected only when id also matched, and since id is unique, nothing would be rejected. INCLUDE avoids that mistake.
A partial index can also include columns:
CREATE INDEX orders_pending_cover_idx
ON orders (created_at)
INCLUDE (customer_id)
WHERE status = 'pending';The query must still imply the predicate status = 'pending', as covered in the partial index chapter, and it must need only created_at and customer_id.
One restriction: included columns must be plain columns. Expressions such as lower(email) are not allowed in the INCLUDE list. To return a computed value from an index, use it as a key column in an expression index.
Costs and limits
Included columns make every index entry larger. A larger index means more pages to read, more memory in the cache, and more work on every insert and on updates that change an included column. An update to a key column or included column also prevents a heap-only tuple (HOT) update, which is a cheaper update path that avoids touching indexes. If total_cents changes often, including it in the index turns cheap updates into expensive ones.
There is also a size cap. A B-tree entry must fit within roughly a third of an index page, which is about 2.7 kilobytes with the default 8 kB page. Wide included columns, such as long text values, can hit that limit and make inserts fail.
A good candidate for INCLUDE has these traits:
- One frequent, latency-sensitive query returns a few narrow columns.
- The extra columns rarely change.
- The table is vacuumed often enough that
Heap Fetchesstays low. - The same query could not be served by an index you already have.
Check the result with EXPLAIN (ANALYZE, BUFFERS) before and after. If Heap Fetches stays high or the plan does not change, drop the index and keep the smaller one.
Building it on a live table
A covering index on a busy table should be built without blocking writes:
CREATE INDEX CONCURRENTLY orders_customer_cover_idx
ON orders (customer_id)
INCLUDE (total_cents);This is the same CONCURRENTLY behavior described in the chapter on live builds. It cannot run inside a transaction block, and a failed build leaves an invalid index that you must drop before retrying.
Exercise
A table has the index CREATE INDEX orders_customer_cover_idx ON orders (customer_id) INCLUDE (total_cents);. For each query, say whether an index-only scan is possible, and why. (a) SELECT total_cents FROM orders WHERE customer_id = 7; (b) SELECT total_cents, status FROM orders WHERE customer_id = 7; (c) SELECT customer_id FROM orders WHERE total_cents > 5000; Then explain what Heap Fetches: 900 on a 1000-row result tells you.
Show answer
(a) Yes. The filter column customer_id is the key, and total_cents is included, so the index holds everything the query needs. (b) No. status is not in the index, so PostgreSQL must visit the heap for it. (c) Not efficiently. The index holds all the needed columns, but total_cents is only an included column, so it cannot be used to search the tree. The condition could only be applied as a filter while reading a large part of the index, and the planner will usually prefer another plan. Heap Fetches: 900 out of 1000 rows means the scan had to visit the heap for most rows because their pages are not marked all-visible in the visibility map. Running VACUUM on the table should reduce this number, unless the table is modified so often that pages never stay all-visible.