Sub topic 8
Adding payload columns with INCLUDE
This chapter assumes you can read a basic EXPLAIN plan and know that a B-tree index stores sorted keys with pointers to heap rows. You should also know what an index-only scan is and why the visibility map matters. The examples use the one-million-row orders table from earlier chapters.
The problem INCLUDE solves
Suppose you run this query often:
SELECT customer_id, total FROM orders WHERE customer_id = 42;An index on customer_id alone finds the matching rows quickly. The index does not store total, so PostgreSQL must visit the heap for every match to read it. The plan is usually an Index Scan or a Bitmap Heap Scan.
You could add total to the key: CREATE INDEX ON orders (customer_id, total). That works, but it makes total part of the sort order. Every internal page of the tree then carries total values, and a unique index would enforce uniqueness on the pair instead of on customer_id. The INCLUDE clause, available since PostgreSQL 11, adds a column as payload only.
The syntax
CREATE INDEX orders_customer_total_idx
ON orders (customer_id) INCLUDE (total);
VACUUM (ANALYZE) orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;customer_id is the search key. total is stored in the leaf entries next to the key but is not used to order the tree. Because every column the query needs is now in the index, the planner can choose an Index Only Scan. After VACUUM, the Heap Fetches line should be near zero.
You will see output similar to this. Your numbers will differ.
Index Only Scan using orders_customer_total_idx on orders
Index Cond: (customer_id = 42)
Heap Fetches: 0An Index Only Scan needs two things: an index that holds every column the query uses, and a visibility map that is mostly current. INCLUDE gives you the first. VACUUM gives you the second.
What is stored where
In a B-tree with INCLUDE, key columns appear in both leaf pages and internal (non-leaf) pages. Included columns appear only in leaf pages. Internal pages exist for navigation, so they only need the key. This keeps the upper levels of the tree small and cache-friendly, which is the main structural benefit over putting the column in the key.
The diagram below shows the layout.
Key columns versus included columns
The two kinds of column differ in what you can do with them.
| Property | Key column | INCLUDE column |
|---|---|---|
| Stored in internal pages | Yes | No |
| Affects sort order | Yes | No |
| Usable in `WHERE` as an index condition | Yes | No |
| Counted in a unique check | Yes | No |
| Can be returned by an index-only scan | Yes | Yes |
| Needs a B-tree operator class | Yes | No |
The last row matters in practice. An included column needs no ordering, so you can include types that have no B-tree operator class, as long as they fit in an index entry. Choose by role:
- Put a column in the key if you filter on it, join on it, or need sorted output from it.
- Put a column in
INCLUDEif you only select it.
An included column cannot be used as a search condition in the index. A filter on total in the WHERE clause is applied to the values read from the index. It does not narrow the range scanned.
Size limits
A B-tree entry must fit in roughly a third of a page, about 2.7 kB with 8 kB pages. Included columns count toward that limit. Wide values such as long text can exceed it, and the insert then fails with an error about the index row size. Including a large text or jsonb column is rarely a good idea. Small fixed-width columns such as integers, numerics and timestamps are the usual choice.
PostgreSQL does not compress included values in the way it can compress table columns. A wide payload column duplicates data from the heap into every leaf entry.
Costs
Every included column has a price.
- Index size. Leaf entries get larger, so fewer fit per page. The index grows and fewer of its pages stay in cache. Compare sizes yourself:
SELECT pg_size_pretty(pg_relation_size('orders_customer_idx')) AS plain,
pg_size_pretty(pg_relation_size('orders_customer_total_idx')) AS covering;- Write overhead. Inserts and deletes must maintain one more index and larger entries. Updates are the sharper edge.
- HOT updates. A heap-only tuple (HOT) update avoids touching indexes, but only when no indexed column changes. PostgreSQL considers a column indexed if it appears anywhere in an index, including in
INCLUDE. If you includetotaland then updatetotal, those updates can no longer be HOT. Each one writes new entries in every index on the table. A column that changes often is a poor payload candidate. - Visibility map churn. Updates clear the all-visible bit on the pages they touch. Until the next
VACUUM, index-only scans on those pages fall back to heap fetches.
The following sequence shows the last point.
UPDATE orders SET total = total + 1 WHERE customer_id = 42;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;
VACUUM orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;The first plan should report Heap Fetches greater than zero. The second should report fewer, or none.
Unique indexes with INCLUDE
In a unique index, only the key columns take part in the uniqueness check. Included columns are payload.
CREATE UNIQUE INDEX orders_id_covering_idx
ON orders (id) INCLUDE (status, total);This enforces that id is unique, and lookups by id can return status and total from the index. If you had written (id, status, total) as the key, two rows with the same id and different status values would be allowed, which defeats the constraint.
UNIQUE and PRIMARY KEY constraints accept INCLUDE too:
ALTER TABLE orders
ADD CONSTRAINT orders_id_key UNIQUE (id) INCLUDE (status);This is useful when you want one index to serve both the constraint and a hot lookup, instead of keeping a second index.
Partial covering indexes
You can combine INCLUDE with a WHERE clause to cover only the rows a query cares about.
CREATE INDEX orders_new_customer_idx
ON orders (customer_id) INCLUDE (total)
WHERE status = 'new';
EXPLAIN
SELECT customer_id, total
FROM orders
WHERE status = 'new' AND customer_id = 42;The index holds only rows with status = 'new', so it is smaller. The query must repeat a condition that implies the index predicate, or the planner cannot use the index. Note that status does not need to be an indexed column for this to work, because the predicate is evaluated when rows are added to the index.
Common mistakes
- Expecting an index-only scan without VACUUM. A freshly loaded table has no all-visible bits. Run
VACUUMfirst. - Selecting an uncovered column. One extra column in
SELECT, such asSELECT *, sends the plan back to the heap. - Filtering on an included column and expecting a range scan. Only key columns define the scanned range.
- Including a frequently updated column. This blocks HOT updates and keeps clearing visibility bits.
- Leaving the old index in place. If
orders_customer_idxis fully replaced by the covering index, drop it. Check usage inpg_stat_user_indexesfirst.
Exercise
A table has a unique constraint required on email. Your hot query is SELECT email, display_name FROM users WHERE email = $1. Write the index definition that enforces uniqueness on email alone and lets the query run as an index-only scan. Then explain why (email, display_name) as the key would be wrong.
Show answer
CREATE UNIQUE INDEX usersemailcoveringidx ON users (email) INCLUDE (displayname); Only the key columns are checked for uniqueness. With (email, display_name) as the key, the same email could appear twice with different display names, so the constraint would no longer guarantee unique emails.
Exercise
You added INCLUDE (total) to an index. Weeks later, EXPLAIN (ANALYZE) shows Heap Fetches in the thousands, and the application updates total nightly. Name two effects of including total that contribute to this, and one fix.
Show answer
Updating total prevents HOT updates, because it is an indexed column, and each update clears the all-visible bit on the pages it touches. Until VACUUM runs, the index-only scan must check the heap for those pages. Fixes: run VACUUM right after the nightly update, tune autovacuum for the table, or remove total from INCLUDE if the benefit does not justify the cost.