Skip to content

Covering and partial indexes

Deep diveConcept

An index finds rows quickly, and then usually goes to the table to read them. A covering index holds the answer itself, so that trip can be skipped. A partial index holds only the rows your query can ever want, so it stays tiny. Here are both, measured on a real table.

01 Two queries, two kinds of waste

An orders table and two everyday queries: a customer’s order totals for their account page, and the ten oldest pending orders for a worker to ship next.

schema.sql
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id int NOT NULL,
status text NOT NULL, -- 'pending' or 'shipped'
total int NOT NULL,
created_at timestamptz NOT NULL,
note text
);
-- 200,000 rows, 20 per customer, spread through the table;
-- 1 in 100 orders is 'pending'.
queries.sql
-- 1. account page
SELECT customer_id, total FROM orders WHERE customer_id = 42;
-- 2. shipping worker
SELECT id FROM orders
WHERE status = 'pending'
ORDER BY created_at
LIMIT 10;

With a plain index on customer_id, query 1 finds its 20 index entries in a couple of page reads, and then reads 20 table pages to fetch total. Query 2 could use an index on (status, created_at), but 99% of that index describes shipped orders the query never asks for. Every result on this page is from Postgres 16, with the table freshly vacuumed.

02 Where an index scan spends its reads

A B-tree entry holds the indexed value and a pointer to the row: a page number and a slot. Anything else the query wants is in the table, which Postgres calls the heap. Rows for one customer were inserted at different times, so they sit on different pages.

Text
Bitmap Heap Scan on orders (actual rows=20 loops=1)
Recheck Cond: (customer_id = 42)
Heap Blocks: exact=20
Buffers: shared hit=20 read=2
-> Bitmap Index Scan on orders_customer_idx (actual rows=20 loops=1)
Index Cond: (customer_id = 42)
Buffers: shared read=2

EXPLAIN (ANALYZE, BUFFERS) counts the pages. The index took 2 page reads. The table took 20, one per row, because each row is on its own page. The index did its job; the trip to the heap is ten times the cost.

03 Covering: put the answer in the index

If every column the query uses is in the index, Postgres can answer from the index alone. INCLUDE (Postgres 11 and later, for B-trees) stores extra columns in the leaf entries without making them part of the key:

SQL
DROP INDEX orders_customer_idx;
CREATE INDEX orders_customer_total_idx
ON orders (customer_id) INCLUDE (total);
Plain index
Bitmap Heap Scan on orders
Recheck Cond: (customer_id = 42)
Heap Blocks: exact=20
Buffers: shared hit=20 read=2
Covering index
Index Only Scan using orders_customer_total_idx
Index Cond: (customer_id = 42)
Heap Fetches: 0
Buffers: shared hit=1 read=3
Plain index on customer_id22 pages2 index pages, then one table page per matching row.
Covering index4 pagesRoot, branch and leaf pages of the index. The table is not opened.

The word that matters is every. Add one more column to the query and the index no longer covers it. SELECT customer_id, total, status went straight back to a Bitmap Heap Scan with 20 heap blocks.

04 Why the index alone is not quite enough

There is a catch. Postgres keeps old row versions around after an UPDATE or DELETE, and an index entry does not say whether its row version is visible to your query. That information lives in the heap. So how can an index-only scan skip the heap?

Through the visibility map: one bit per table page, set by VACUUM when every row on the page is visible to every transaction. If the bit is set, the index entry can be trusted. If not, Postgres reads the page to check. Here is the scan on a toy table of six pages, where page 3 was changed after the last vacuum:

An Index Only Scan, checking the visibility map
Step 1 of 5
Index leaf · (customer_id) INCLUDE (total)
41 · 120
42 · 15
42 · 300
42 · 80
43 · 55
Visibility map · one bit per table page
p1 ✓
p2 ✓
p3 ✗
p4 ✓
p5 ✓
p6 ✓
Table pages (the heap)
p1
p2
p3
p4
p5
p6
Result rows
Empty
  • reading now
  • checked, all fine
  • new result row
  • answer
  • not read

The query wants customer_id and total for customer 42. Both are in the index, so the plan is an Index Only Scan. Postgres has walked down the tree to the leaf where the 42s start. Nothing is read yet.

0 table pages read

The same thing on the real table. Five of customer 42’s rows were updated, which clears the bits of their pages until the next vacuum:

After 5 updates
Index Only Scan using orders_customer_total_idx
Index Cond: (customer_id = 42)
Heap Fetches: 5
Buffers: shared hit=9
After VACUUM
Index Only Scan using orders_customer_total_idx
Index Cond: (customer_id = 42)
Heap Fetches: 0
Buffers: shared hit=4

An Index Only Scan is only as good as its Heap Fetches. On a table that changes faster than autovacuum visits it, most pages are not all-visible, every match costs a heap read again, and you pay for the bigger index for nothing. On a copy of the table that had never been vacuumed, the planner did not even choose the index-only plan; it picked a bitmap heap scan.

05 INCLUDE or a second key column?

CREATE INDEX ON orders (customer_id, total) would also cover query 1. Both store total in the leaf entries. The difference is whether total is part of the sort order.

(customer_id, total) against (customer_id) INCLUDE (total)
PropertyKey columnINCLUDE column
Sorted by it within a customeryesno
Can start or stop the scan (`Index Cond`)yesno; only filters entries
Stored in upper tree levelsyesno, leaf pages only
Counts in a UNIQUE checkyesno
Needs a B-tree operator for its typeyesno

Use a key column when queries filter or sort by it: WHERE customer_id = 42 ORDER BY total reads entries already in order. Use INCLUDE when the column is only carried along to be returned. Its best-known use is a unique index that must stay unique on the key alone: CREATE UNIQUE INDEX ON users (id) INCLUDE (email) keeps id unique while also covering lookups of email.

06 Partial: index only the rows you ask for

Query 2 only ever wants pending orders, 2,000 of the 200,000. A partial index has a WHERE clause, and only rows that match it get an entry:

SQL
-- the full index: every order
CREATE INDEX orders_status_created_idx ON orders (status, created_at);
-- the partial index: pending orders only
CREATE INDEX orders_pending_created_idx ON orders (created_at)
WHERE status = 'pending';
(status, created_at)6,184 kBAn entry for every order, shipped or not.
(created_at) WHERE status = 'pending'64 kBEntries for the 1% of orders the query can return.

Both sizes come from pg_relation_size on the same table. With both indexes present, the planner picked the partial one; the plan reads 12 pages to return 10 ids:

Text
Limit (actual rows=10 loops=1)
-> Index Scan using orders_pending_created_idx on orders (actual rows=10 loops=1)
Buffers: shared hit=12

It is also cheaper to keep. Inserting a shipped order adds nothing to the partial index, and a smaller index is more likely to stay in memory. Notice the index does not store status at all: every entry has the same one, so the WHERE clause says it once for all of them.

07 The query must promise the index’s WHERE

The planner uses a partial index only when it can prove, from the query text, that every row the query wants satisfies the index’s condition. It does not look at the data to check. Two real cases where it cannot:

status = 'shipped'
Limit
-> Gather Merge
-> Sort
Sort Key: created_at
-> Parallel Seq Scan on orders
Filter: (status = 'shipped'::text)
Generic plan ($1)
Limit
-> Gather Merge
-> Sort
Sort Key: created_at
-> Parallel Seq Scan on orders
Filter: (status = $1)

On the left, shipped orders are simply not in the index. On the right, a prepared statement planned once for any parameter cannot use it either, since $1 might not be pending; the plan came from PREPARE with plan_cache_mode = force_generic_plan. Drivers and ORMs often prepare statements, so write the constant into the SQL when you depend on a partial index.

The same idea gives you a rule that ordinary constraints cannot express. With soft deletes, an email must be unique among live users but may repeat among deleted ones:

SQL
CREATE UNIQUE INDEX users_live_email_idx
ON users (email)
WHERE deleted_at IS NULL;

08 When it bites

SELECT * ... with a covering indexOne extra columnSELECT * or a single new column in the query sends every match back to the heap. Check that the plan still says Index Only Scan after the query changes.
Heap Fetches: 18000A busy table and no vacuumIf pages are rarely all-visible, an index-only scan reads the heap anyway. Tune autovacuum for the table, or accept that covering will not pay off there.
INCLUDE (a, b, c, d)Covering everythingEach included column makes every leaf entry bigger and every write dearer. Cover the few queries that run constantly, not every query.
WHERE status IN ('pending', 'held')A query wider than the indexAn index WHERE status = 'pending' cannot answer this, since held rows are missing. Widen the index condition or split the query.
WHERE created_at > now() - interval '1 day'A moving conditionThe WHERE of an index may only use immutable functions, and now() is not one: Postgres refuses with functions in index predicate must be marked IMMUTABLE. Index on a flag or a fixed date you rebuild from time to time instead.

09 Check yourself

Question

There is an index on (email) INCLUDE (name). Which query can be an Index Only Scan?

Question

An Index Only Scan shows Heap Fetches: 950 for 1,000 rows. What is the likely cause?

Question

Index: ON orders (created_at) WHERE status = 'pending'. Which query can use it?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?