Sub topic 4
The visibility map: why the index alone is not enough
This chapter assumes you know basic SQL, understand a B-tree index at a high level, and can read a simple EXPLAIN plan. It also assumes you have the one-million-row orders table from the earlier chapters, with the index orders_customer_total_idx on (customer_id) INCLUDE (total). The previous chapter showed that an index-only scan can answer a query without reading the table. This chapter explains why PostgreSQL still sometimes visits the table, and which structure decides when it can skip it.
The problem: the index does not know who can see a row
PostgreSQL uses multiversion concurrency control (MVCC). An UPDATE does not overwrite a row. It writes a new row version (a tuple) and marks the old one as expired. Different transactions can see different versions at the same moment.
Whether a tuple is visible to your transaction depends on two fields in its heap tuple header: xmin, the transaction that created it, and xmax, the transaction that deleted or replaced it. Your snapshot is compared against these.
Index entries do not carry xmin or xmax. A B-tree entry holds the key values (and any INCLUDE payload) plus a tuple identifier (TID) that points to a heap page and a slot. Suppose the index contains an entry for customer_id = 42. The index cannot tell you whether that entry belongs to a row version your transaction is allowed to see. It could belong to a deleted row, to an old version, or to a row inserted by a transaction that has not committed.
So even when every column the query needs is in the index, PostgreSQL cannot return the row from the index alone. It must check visibility somewhere. Checking the heap tuple would defeat the purpose of an index-only scan. The visibility map avoids that check for most pages.
What the visibility map is
The visibility map (VM) is a small side file for each table, stored as the _vm fork of the relation. It holds two bits per heap page:
| Bit | Meaning |
|---|---|
| all-visible | Every tuple on the page is visible to every current and future transaction. |
| all-frozen | Every tuple on the page is frozen, so even anti-wraparound vacuums can skip the page. |
Only the all-visible bit matters for index-only scans. The all-frozen bit helps VACUUM avoid rereading old data.
The map is tiny. Two bits per 8 kB page means one VM page covers tens of thousands of heap pages, so it usually stays in memory.
How an index-only scan uses it
For each index entry that matches the query, the executor does the following:
- It reads the TID from the entry and finds the heap page number.
- It looks up that page's all-visible bit in the visibility map.
- If the bit is set, it returns the values straight from the index entry. The heap page is never read.
- If the bit is not set, it fetches the heap tuple, checks
xminandxmaxagainst the snapshot, and returns the row only if it is visible. This is a heap fetch.
An index-only scan is therefore not a guarantee that the heap is untouched. It is a plan that reads the heap only for pages that are not marked all-visible. A "fresh" table behaves like a normal index scan in cost until the map is populated.
When bits are set and cleared
The all-visible bit changes in only two ways:
VACUUMsets it. While vacuuming a page, if all tuples on it are visible to all transactions (no dead tuples, nothing recently inserted or deleted that an old snapshot might still need), vacuum sets the bit. Autovacuum does this too.- Data changes clear it. Any
INSERT,UPDATEorDELETEthat touches a page clears the bit for that page right away. The clearing is WAL-logged, so it survives a crash.
A plain ANALYZE does not set the bit. It gathers statistics only. It does refresh pg_class.relallvisible, but it does not change the map.
This asymmetry has a practical result. Clearing is immediate and setting is delayed. A table with steady writes spreads its modifications across many pages, and each one loses its bit until a later vacuum visits it.
A long-running transaction can also hold back vacuum. Vacuum cannot treat a tuple as visible to everyone while an older snapshot might not see it, so pages touched recently may stay unmarked even after VACUUM runs.
Looking at the map
The planner and you can both inspect how much of the table is marked. First, the cheap estimate in pg_class, which VACUUM and ANALYZE update. Then the exact numbers from the pg_visibility extension.
SELECT relname, relpages, relallvisible
FROM pg_class
WHERE relname = 'orders';
CREATE EXTENSION IF NOT EXISTS pg_visibility;
SELECT * FROM pg_visibility_map_summary('orders');relallvisible divided by relpages is the fraction of pages the planner believes are all-visible. The planner uses it to estimate how many heap fetches an index-only scan will need, and it folds that into the cost. If the fraction is low, the planner may prefer a plain index scan or bitmap scan, because the index-only plan promises savings it cannot deliver.
pg_visibility_map_summary returns all_visible and all_frozen page counts read from the map itself. Use it when you want the real state rather than the planner's cached estimate. The extension needs sufficient privileges to create, and it is not installed by default.
Watching the map get cleared and refilled
The following sequence shows the whole cycle. It assumes VACUUM (ANALYZE) orders has already run after the index was built, so most pages are marked.
UPDATE orders SET total = total + 1 WHERE customer_id = 42;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;
VACUUM orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;The UPDATE rewrites roughly a hundred rows for that customer, spread over many heap pages. Each page it touches loses its all-visible bit. The first plan reports Heap Fetches greater than zero, because the matching index entries now point to pages that are not marked. After VACUUM, the pages are marked again, and the second plan should report fewer fetches, ideally zero.
The relevant lines look like this. The numbers are illustrative and will differ on your machine.
Index Only Scan using orders_customer_total_idx on orders
Index Cond: (customer_id = 42)
Heap Fetches: 104
Buffers: shared hit=212
Index Only Scan using orders_customer_total_idx on orders
Index Cond: (customer_id = 42)
Heap Fetches: 0
Buffers: shared hit=4Two points about reading this output:
Heap Fetchescounts index entries that needed a heap visit, not distinct heap pages. Several entries on one page count separately.- The
Buffersline shows the benefit. Fewer fetches means fewer buffer touches. A plan with a highHeap Fetchescount still says "Index Only Scan", but it does close to the work of a regular index scan.
Gotchas
- A fresh bulk load has no bits set. After the
INSERT ... SELECT generate_seriesthat buildsorders, no page is marked all-visible until a vacuum runs. This is why the examples runVACUUM (ANALYZE)right after creating an index. Without it, an index-only scan would fetch from the heap for almost every row. ANALYZEalone is not enough. It may updaterelallvisible, but it does not set bits. Only vacuum does.- Hot pages stay unmarked. On a table where recent rows are updated constantly, the pages that contain them rarely keep their bits. Queries over old, stable data do well. Queries over recent data do not.
- A correct plan can still be slow. The plan shape tells you the planner chose an index-only scan. Only
Heap Fetchestells you whether it works.
Summary of the mechanism
- Index entries have no visibility data, so an index alone cannot decide which rows a transaction may see.
- The visibility map records, per heap page, whether all tuples are visible to everyone.
- An index-only scan checks the map for each entry. A set bit means no heap visit. A cleared bit means a heap fetch.
VACUUMsets bits. Writes clear them.Heap FetchesinEXPLAIN (ANALYZE)measures how often the map did not help.
Exercise
A table was bulk loaded with 5 million rows and indexed with a covering index. Right after creating the index, EXPLAIN (ANALYZE) for a query that the index covers shows an Index Only Scan with a large Heap Fetches value. Why does this happen, what single command is the usual fix, and why does ANALYZE alone not fix it?
Show answer
The bulk load wrote new tuples, and no page has its all-visible bit set until a vacuum has processed it. Each index entry therefore needs a heap visit to check xmin and xmax, which is what Heap Fetches counts. Running VACUUM (or VACUUM (ANALYZE)) sets the bits for pages whose tuples are visible to everyone, after which Heap Fetches should drop toward zero. ANALYZE collects statistics only. It can refresh relallvisible, but it never sets bits in the visibility map.