Sub topic 9
Choosing key columns versus included columns
This chapter assumes you can read a basic EXPLAIN plan and know that a B-tree index keeps its entries sorted. It also assumes you know what an index-only scan is and why it needs the visibility map. The examples use the orders table from earlier in the tutorial.
Once you decide to build a covering index, you have to place every column in one of two groups. A column can be a key column or an included column. The placement changes which queries the index can serve, how large it is, and what it enforces.
What each group does
Key columns are the columns listed in the main parentheses of CREATE INDEX. PostgreSQL sorts the index entries by them and copies them into the upper levels of the tree. The upper levels are the pages that direct a search toward the right leaf. Because of this, key columns can drive the search itself: equality conditions, range conditions, ORDER BY, and merge joins.
Included columns are listed after INCLUDE. PostgreSQL stores their values only in the leaf entries, next to the key. They play no part in ordering and are absent from the upper levels. Their only job is to be returned, so an index-only scan can read them without visiting the heap.
CREATE INDEX orders_cust_created_idx
ON orders (customer_id, created_at)
INCLUDE (total);In this index, customer_id and created_at are key columns, and total is payload.
A worked comparison
Suppose the application shows a customer's ten most recent orders:
SELECT created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;The WHERE condition uses customer_id, and the ORDER BY uses created_at. Both must be key columns, in that order. The index finds customer 42's entries, and they are already sorted by created_at. PostgreSQL then reads the last ten in reverse. The query also returns total, but it never filters or sorts on it, so total can be payload.
VACUUM (ANALYZE) orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;You should see an Index Only Scan Backward using orders_cust_created_idx. It has no separate sort step, and Heap Fetches is near zero after the VACUUM.
Why not put everything in the key?
A three-column key (customer_id, created_at, total) would also allow an index-only scan for this query. So why use INCLUDE? The two designs differ in several ways.
| Property | Key column | Included column |
|---|---|---|
| Stored in leaf entries | Yes | Yes |
| Stored in upper-level pages | Yes | No |
| Affects sort order | Yes | No |
| Usable as a search condition or for `ORDER BY` | Yes | No |
| Needs a B-tree operator class (a defined ordering for the type) | Yes | No |
| Counts toward uniqueness | Yes | No |
| Allowed to be an expression | Yes | No, plain columns only |
Three consequences follow from this table.
- Smaller upper levels. Every key column is repeated in the upper-level pages. Wide keys mean fewer entries per page, a taller tree, and more pages to read for each lookup. Payload in
INCLUDEleaves the upper levels as narrow as the real search key. - Any data type can be payload. A key column needs an ordering. An included column does not. A type with no B-tree operator class can still be included.
- Your intent is documented. When the next developer reads
INCLUDE (total), they knowtotalis not meant for searching.
You can compare the sizes yourself:
CREATE INDEX orders_cust_created_total_key_idx
ON orders (customer_id, created_at, total);
SELECT indexrelid::regclass AS index_name,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_index
WHERE indrelid = 'orders'::regclass
ORDER BY pg_relation_size(indexrelid) DESC;On a table like this one, the two designs have similar total size because the leaf level dominates. The INCLUDE version saves a little in the upper levels. The real gain depends on how wide the payload columns are. Measure on your own data before treating the saving as large.
When a column belongs in the key
Put a column in the key when any of these is true:
- It appears in a search condition that you want the index to narrow on. Conditions on payload columns cannot narrow the scan. At best they are checked after the entries have been found.
- You need the index order.
ORDER BY created_atcan only use the index order ifcreated_atis a key column in the right position. - It must be part of a uniqueness rule. Only key columns count (see the next section).
- You need an expression.
INCLUDEaccepts column names only, solower(email)must be a key column.
Key column order still matters. As a rule, put equality columns first and the range or sort column last. The earlier query follows that pattern: customer_id is compared with =, and created_at supplies the order.
When a column belongs in INCLUDE
Use INCLUDE for columns that satisfy all of these:
- They are read by the query but not used to filter or sort.
- They are fairly narrow, or the query is frequent enough to justify the space.
- They change rarely, because every change touches the index.
A common case is a lookup by a unique key that returns a few display columns. This was the purpose of the unique covering index in the topic plan, and it is covered in its own chapter.
Costs to keep in mind
The write-cost chapter covers this in depth. In short, an included column makes each leaf entry larger. Larger entries mean fewer entries per page and a bigger index. Updating an included column also counts as updating an indexed column, so the update cannot be a HOT update (one that skips index maintenance). The total column in this chapter's index is a good example. If your application updates total often, you pay for that in write cost.
Two further details matter when you choose placement:
- Deduplication is not available. B-tree deduplication, which stores repeated key values compactly, does not work on indexes that have
INCLUDEcolumns. A low-cardinality key with payload columns therefore cannot benefit from it. - Entry size has a ceiling. A B-tree entry must fit about one third of a page, roughly 2.7 kB with the default 8 kB page. Including a large
textcolumn can make inserts fail with an "index row size exceeds maximum" error. A largetextcolumn is a poor payload candidate.
Which columns can also be filtered?
Sometimes a query filters on a payload column, for example WHERE customer_id = 42 AND total > 400. The index cannot use total to narrow its search, because it is not sorted by total within a customer. PostgreSQL still avoids the heap in this case. It can check the condition against the value stored in the index entry. The scan reads all of customer 42's entries and discards the ones that fail. If the filter is selective and you run it often, promoting total into the key as (customer_id, total) lets the index skip non-matching entries entirely. The trade-off is that you lose the created_at ordering unless you add it too.
Summary of the rule
Key columns decide which entries the index can find and in what order. Included columns decide what the index can return without a heap visit. Start with the smallest key that serves the search and ordering, then add payload only for the columns that would otherwise force heap fetches.
Exercise
A query is SELECT status, total FROM orders WHERE customer_id = 7 AND created_at >= now() - interval '30 days' ORDER BY created_at;. Write an index that supports an index-only scan for it. State which columns are key columns, which are included, and why.
Show answer
CREATE INDEX ON orders (customer_id, created_at) INCLUDE (status, total); The key columns are customer_id (equality condition, placed first) and created_at (range condition and ORDER BY, placed last so the entries are already sorted). status and total are only returned, so they are payload. The index-only scan also needs the pages to be marked all-visible, so run VACUUM and check that Heap Fetches is low.
Exercise
Why can an index with INCLUDE (payload) be a better choice than putting payload in the key, even when both allow an index-only scan?
Show answer
Included columns are stored only in the leaf entries, so the upper-level pages stay narrow and the tree stays shallower. Payload columns also need no sort order or operator class, and they do not become part of a uniqueness rule. The cost is that the index cannot use them to narrow a search or to provide ordering.