index-only scans and INCLUDE
answering from the index alone, the visibility map that makes it legal, and Heap Fetches: 0.
- address
- everything.indexes.index_only_scans
- part
- part 8, indexes, from the outside
- chapter
- chapter 5 of 12
- reading time
- 8 min
if every column a query needs is in the index, postgres can answer from the index alone: an index-only scan. the catch is visibility. the index doesn't know which row versions your snapshot can see, so postgres checks the visibility map, and for every page not marked all-visible it goes to the heap anyway. EXPLAIN counts those trips as Heap Fetches.
a freshly vacuumed table: Heap Fetches: 0. a table nobody vacuums: an index-only scan in name only.
the picture
you know how the index at the back of a book sometimes answers the question by itself? "is there anything about saffron?" the index says page 212, and you don't need to open page 212 to know the answer is yes.
a query that only asks for indexed columns is that question. the index has the values. what it doesn't have is MVCC: an index entry points at a row version, and only the heap knows whether that version is committed, deleted, or too new for you (visibility rules). so before trusting the entry, postgres asks a much smaller question: is that heap page marked all-visible? if yes, every version on it is visible to everyone and the index entry can be trusted. if no, fetch the heap page and check.
step through a real run: a never-vacuumed copy of orders with an index on customer_id, and a query that only needs customer_id.
a fresh table: no page is marked all-visible yet. postgres knows, and doesn't even try an index-only scan.
o, one per heap page, . before VACUUM, the forced index-only scan makes 1,321 heap fetches, one per row. after VACUUM, 0, and 4 pages read in all. the UPDATE clears 4 bits, and the next scan makes 62 heap fetches into exactly those pages.notice the first step: the planner didn't even try an index-only scan. it knows how many pages are all-visible (pg_class.relallvisible, updated by VACUUM), and an index-only scan over a table with none is just an index scan with extra steps. forcing it shows why: 1,321 heap fetches for 1,321 rows.
run it
the same sequence, in the browser. a copy of orders that nothing has vacuumed yet:
CREATE TABLE o (LIKE orders);
INSERT INTO o SELECT * FROM orders ORDER BY id;
CREATE INDEX o_customer ON o (customer_id);
ANALYZE o;
SELECT count(*) FILTER (WHERE all_visible) AS all_visible, count(*) AS pages
FROM pg_visibility_map('o');| all_visibleint8 | pagesint8 |
|---|---|
| 0 | 83 |
zero of 83. ANALYZE gathers statistics but never touches the visibility map; only VACUUM sets the bits. here's the query:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT customer_id, count(*) FROM o
WHERE customer_id <= 100
GROUP BY customer_id ORDER BY customer_id;a bitmap scan over all 83 heap pages. now vacuum, and run it again:
VACUUM o;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT customer_id, count(*) FROM o
WHERE customer_id <= 100
GROUP BY customer_id ORDER BY customer_id;Index Only Scan, Heap Fetches: 0, a few pages read instead of 86. and no sort either: the index hands the rows over in customer_id order, so a GroupAggregate can count them as they go by.
UPDATE o SET status = 'refunded' WHERE id IN (5, 4000, 8000);SELECT id, customer_id FROM o WHERE id IN (5, 4000, 8000) ORDER BY id;
UPDATE o SET status = 'refunded' WHERE id IN (5, 4000, 8000);
SELECT blkno FROM pg_visibility_map('o') WHERE NOT all_visible ORDER BY blkno;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT customer_id, count(*) FROM o
WHERE customer_id <= 100
GROUP BY customer_id ORDER BY customer_id;| idint4 | customer_idint4 |
|---|---|
| 5 | 673 |
| 4000 | 1017 |
| 8000 | 545 |
| blknoint8 |
|---|
| 0 |
| 33 |
| 66 |
| 82 |
none of the three is in the result. four pages lost their bit anyway: the three pages the old versions sit on, and the last page, where the new versions went. 62 heap fetches, all into those four pages. the other entries are still answered from the index. on a busy table this is the steady state: Heap Fetches climbs as writes clear bits, and drops back to zero each time VACUUM catches up. that's one more reason autovacuum settings matter for read performance, not only for bloat.
one level deeperwhere the bits come from
the visibility map is a separate fork of the table (_vm), two bits per heap page: all-visible and all-frozen. VACUUM sets all-visible when every tuple on the page is visible to every transaction, and any insert, update or delete on the page clears it, as part of the same WAL-logged change. index-only scans read the all-visible bit; VACUUM itself uses both to skip pages. the free space map and the visibility map shows the fork, and VACUUM the pass that sets it.
INCLUDE: carrying a column you don't search on
the query above only needed customer_id. ask for status too, and the index can't answer any more. you could index (customer_id, status), but if you never search or sort by status, it doesn't need to be part of the key. INCLUDE stores it in the leaf entries as payload: not sorted, not searchable, just there to be read.
the index has customer_id but not status, so every match is a visit to the heap: a bitmap scan over the orders' pages.
INCLUDE (status). without it, the index finds 7 entries and the heap has to be read for each status. with it, an index-only scan. a query on status alone can't use the INCLUDE column to search.CREATE INDEX orders_customer_inc ON orders (customer_id) INCLUDE (status);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT customer_id, status FROM orders WHERE customer_id = 42;shop was vacuumed when it loaded, so orders is all-visible and Heap Fetches: 0 right away.
INCLUDE vs another key column:
(customer_id, status) | (customer_id) INCLUDE (status) | |
|---|---|---|
| index-only scan for both columns | yes | yes |
WHERE customer_id = 42 AND status = 'paid' narrows the scan | yes | status is checked, not searched |
ORDER BY customer_id, status without a sort | yes | no |
| in internal pages | yes | no, leaf entries only |
allowed on a UNIQUE index without changing what's unique | no | yes |
the last row is the one that made INCLUDE worth adding: CREATE UNIQUE INDEX ON orders (id) INCLUDE (status) keeps id unique and still covers lookups that want the status. adding status as a key column would make (id, status) the unique thing, which isn't the rule you wanted.
keylines
- index-only scan: every column the query needs is in the index.
- the visibility map decides whether the heap is skipped, page by page.
- Heap Fetches: 0 needs a recent VACUUM. writes clear bits for whole pages.
- INCLUDE carries columns for covering without making them part of the key.