Sub topic 7
Designing a covering index
A covering index holds every column a query needs from a table. PostgreSQL can then answer the query from the index alone, which makes an index-only scan possible. This chapter assumes you can read basic EXPLAIN output. It also assumes you know that an index-only scan skips the heap only when the visibility map allows it, as covered in the previous chapters. Here the focus is on deciding which columns go into an index and when the result is worth its cost.
Coverage is a property of a query and an index together
An index is never "covering" in general. It covers a specific query. If the index has customer_id and total, it covers this query:
SELECT customer_id, total FROM orders WHERE customer_id = 42;It does not cover this one, because status is missing:
SELECT customer_id, total, status FROM orders WHERE customer_id = 42;PostgreSQL considers an index-only scan only when every column the query references for that table is available in the index. "References" is broader than the select list. It includes WHERE, ORDER BY, GROUP BY, JOIN conditions and any function arguments. One uncovered column anywhere in the query sends the planner back to a regular Index Scan or Bitmap Heap Scan.
A design procedure
Start from the query, not from the table. For each important query, work through these steps.
- List every column of the table that the query references, in all clauses.
- Pick the columns used to find rows. These are equality and range conditions in
WHERE, plus the columns that give the order inORDER BY. They become key columns. - Treat the remaining columns, which are only read for output, as payload candidates.
- Check that each payload column is small and that the extra index size is acceptable.
- Create the index, run
VACUUM, and confirm the plan withEXPLAIN (ANALYZE, BUFFERS).
Worked example: one query, several designs
The examples use the orders table with one million rows from earlier in the tutorial. Take this query:
SELECT created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;The columns referenced are customer_id, created_at and total. customer_id is the search column. created_at provides the order. total is only output. Following the procedure gives this index:
CREATE INDEX orders_cust_created_idx
ON orders (customer_id, created_at) INCLUDE (total);
VACUUM (ANALYZE) orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;The key (customer_id, created_at) lets PostgreSQL find the rows for customer 42 and read them already sorted. A B-tree can be scanned backward, so you do not need created_at DESC in the definition for this query. total rides along in the leaf entries. The plan should show an Index Only Scan Backward with a small Heap Fetches count.
This index serves a second purpose. Without the ORDER BY and LIMIT, the same index still covers the query. It also covers any query that filters on customer_id and reads only created_at and total.
Matching query shapes to indexes
| Query shape | Columns referenced | Reasonable index |
|---|---|---|
| Lookup with two output columns | `customer_id`, `total` | `(customer_id) INCLUDE (total)` |
| Filter, sort, limit | `customer_id`, `created_at`, `total` | `(customer_id, created_at) INCLUDE (total)` |
| Group and count | `customer_id`, `status` | `(customer_id, status)` |
| `SELECT *` | every column | None. Cover a narrower select list instead |
The group-and-count row needs no payload column at all:
CREATE INDEX orders_cust_status_idx ON orders (customer_id, status);
SELECT status, count(*)
FROM orders
WHERE customer_id = 42
GROUP BY status;status here is a key column because it is part of the grouping. Putting it in the key means the index entries for one customer are already ordered by status.
Extra key columns or INCLUDE?
You can add a payload column in two ways. The first is to make it another key column: (customer_id, total). The second is to use INCLUDE: (customer_id) INCLUDE (total). Both allow an index-only scan for the first query above. The next chapter covers the mechanics of INCLUDE, and the chapter after it covers the choice in detail. The practical rule for design is this:
- A column you search or sort by belongs in the key.
- A column you only read belongs in
INCLUDE, unless it also has to take part in a uniqueness rule, which a later chapter covers.
An extra key column has to be comparable with a B-tree operator class. An included column has no such requirement. It is stored as-is in the leaf entry.
Choosing payload columns
Every column you add makes every index entry larger. Bigger entries mean fewer entries per page, a larger index, and more pages to read and keep in cache. Judge each candidate on these points.
- Width. Small fixed-width columns such as
integer,bigint,numeric(10,2)andtimestamptzare good candidates. Longtextvalues such asnoteare poor ones. - Index entry limit. A B-tree entry has to fit within roughly a third of a page, about 2.7 kB with 8 kB pages. Rows that exceed it fail on insert. Wide values can also be compressed or moved out of line, which weakens the benefit.
- Change rate. A column that is updated often makes the index expensive to maintain and clears visibility map bits on the heap pages involved.
- Query value. A column that appears in one rarely run report rarely justifies the space. A column that appears in a hot lookup does.
Measure the size instead of guessing:
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;Compare orders_customer_idx (key only) with orders_customer_total_idx (with total). The second one is larger. The question is whether the saved heap visits repay that growth.
Limits of coverage
Even a correctly designed covering index sometimes does not produce an index-only scan.
- Visibility. The planner still needs the visibility map. If many heap pages are not all-visible,
Heap Fetchesstays high and the benefit shrinks. This is why the design step ends withVACUUMand a plan check. - Cost estimates. If the query returns a large fraction of the table, a sequential scan can still be cheaper than any index plan.
- Expressions. An index on
lower(email)does not give the planner the rawemailcolumn. A query that selectsemailis not covered by that index. - Index type. Not every index access method can return column values. A later chapter lists which ones can.
Verifying the design
After creating the index, always check three things in the plan: the node type (Index Only Scan), the Heap Fetches value, and the Buffers counts. If the node type is a plain Index Scan, a column is probably missing from the index. If the node is an Index Only Scan but Heap Fetches is close to the number of rows returned, the index covers the query but the visibility map does not. Run VACUUM and compare again.
Exercise
A query is SELECT status, total FROM orders WHERE customer_id = 7 AND created_at >= now() - interval '30 days'. List the columns it references and propose a covering index. Which columns are keys and which are payload?
Show answer
The query references status, total, customer_id and created_at. The search columns are customer_id (equality) and created_at (range), so they form the key in that order: (customer_id, created_at). status and total are only output, so they can be payload: CREATE INDEX ON orders (customer_id, created_at) INCLUDE (status, total);. The equality column goes before the range column so the index narrows the search as much as possible.
Exercise
You create (customer_id) INCLUDE (total) and the plan for SELECT customer_id, total, note FROM orders WHERE customer_id = 42 still shows a Bitmap Heap Scan. Why, and what are your options?
Show answer
The query references note, which is not in the index, so no index-only scan is possible and the heap must be visited. You can drop note from the select list if it is not needed. You can also accept the heap visit. Adding the wide note column to the index would make it much larger and is usually a poor trade.