Video in progress

When does an index-only scan really not touch the table, and what is the visibility map's role in that?

An index-only scan works when all the needed columns are in the index, but Postgres consults the visibility map to check row visibility. If a page isn't "all-visible", it still has to go to the table.

📖 Answer

Postgres doesn't store transaction visibility information (xmin/xmax) in the index. So whether a row found through the index is visible to the snapshot is known only in the heap. The visibility map is one bit per page: "every row on this page is visible to every transaction". If the bit is set, it doesn't go to the heap.

CREATE INDEX idx_order_customer ON orders (customer_id) INCLUDE (status, total);

EXPLAIN (ANALYZE, BUFFERS)
SELECT status, total FROM orders WHERE customer_id = 42;
-- Index Only Scan using idx_order_customer on orders
--   Heap Fetches: 0     <- good

If Heap Fetches is large, the visibility map is stale. VACUUM sets the bit, and any update clears it. On a write-heavy table, an index-only scan may in practice be no different from a regular index scan.

INCLUDE (PG11+) columns aren't part of the index key, just "payload": you can't search or sort by them, but they help return the query from the index. They're also handy for adding extra columns to a unique index, since uniqueness stays on the key columns only.