Sub topic 14
The Visibility Map and Index-Only Scans
This chapter assumes you know how xmin and xmax mark row versions, how snapshots decide visibility, and what VACUUM does with dead tuples. It also assumes you can read basic EXPLAIN output. Here we look at the small data structure that lets PostgreSQL skip visibility checks, and at the query plans that depend on it.
The problem: indexes know nothing about visibility
An index entry points to a heap tuple, but it does not contain that tuple's xmin or xmax. The index can't tell you whether the version it points to is visible to your snapshot. It could point to a dead version, a version created by an uncommitted transaction, or a live one.
A plain index scan therefore does two steps for every matching entry:
- Find the entry in the index.
- Fetch the heap page and apply the visibility rules to the tuple.
Step 2 is often the expensive one, because it adds random heap I/O. If the query only needs columns that are already in the index, that heap visit is wasted work, unless it is needed to check visibility. The visibility map removes most of those visits.
What the visibility map is
The visibility map (VM) is a separate file for each table and each materialized view. It is stored as the table's _vm fork, next to the main heap file. It holds two bits for every heap page:
| Bit | Meaning when set |
|---|---|
| all-visible | Every tuple on the page is visible to all current and future transactions. No dead tuples and no recent changes exist on the page. |
| all-frozen | Every tuple on the page is frozen. Wraparound freezing can skip the page. |
One 8 KB VM page covers tens of thousands of heap pages, so the map is tiny and stays cached.
The two bits are maintained asymmetrically:
- VACUUM sets a bit only after it has checked every tuple on the page. All tuples must be visible to every snapshot, which means their xmin is older than the oldest snapshot's horizon, and none has a live xmax.
- Any INSERT, UPDATE or DELETE on the page clears its bits immediately, in the same operation that changes the page.
So a set bit is a guarantee, while a clear bit only means "not known to be all-visible". Pages that change often stay clear until a later VACUUM revisits them.
How an index-only scan uses it
An index-only scan reads the index entry, then asks the VM about the heap page the entry points to.
- If the page is all-visible, the tuple is visible to your snapshot too. The executor returns the value from the index and never touches the heap.
- If the page is not all-visible, the executor fetches the heap tuple and checks visibility the normal way. This is called a heap fetch.
An index-only scan is not a different kind of index. It is a plan type that the planner may choose when two conditions hold:
- Every column the query needs (in the select list, in
WHERE, and elsewhere) is available from the index. - The index type can return its stored values. B-tree can. GiST and SP-GiST can for some operator classes. GIN generally can't.
Seeing it in a plan
Create a table and an index, then compare plans before and after VACUUM.
CREATE TABLE events (
id int PRIMARY KEY,
user_id int NOT NULL,
payload text
);
INSERT INTO events
SELECT g, g % 1000, repeat('x', 100)
FROM generate_series(1, 100000) AS g;
ANALYZE events;
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM events WHERE id < 5000;Right after the load, no page has its all-visible bit set, because nothing has run VACUUM on the table yet. The planner knows this from pg_class.relallvisible, so it may choose a different plan, or an Index Only Scan with many heap fetches. Now vacuum and repeat:
VACUUM (ANALYZE) events;
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM events WHERE id < 5000;The plan should now contain a line like this:
Index Only Scan using events_pkey on events (actual time=... rows=4999 loops=1)
Index Cond: (id < 5000)
Heap Fetches: 0Heap Fetches is the number to watch. It counts the index entries that had to go to the heap because the VM bit was clear. 0 means the VM did all the work.
Next, change some rows and look again:
UPDATE events SET payload = 'changed' WHERE id <= 100;
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM events WHERE id < 5000;The pages holding the updated rows lost their all-visible bits. Heap Fetches is now above zero, and it counts every index entry that points into those pages, not just the 100 updated rows. It stays that way until VACUUM or autovacuum sets the bits again.
Inspecting the map directly
The pg_visibility extension, shipped with PostgreSQL's contrib modules, exposes the bits.
CREATE EXTENSION IF NOT EXISTS pg_visibility;
-- Totals for the whole table
SELECT * FROM pg_visibility_map_summary('events');
-- Bits for one heap page
SELECT * FROM pg_visibility_map('events', 0);
-- The planner's cached count
SELECT relpages, relallvisible
FROM pg_class
WHERE relname = 'events';pg_visibility_map_summary returns all_visible and all_frozen page counts. Compare them with relpages to see what fraction of the table an index-only scan can answer without the heap. relallvisible is updated by VACUUM and ANALYZE, and the planner uses it to estimate how many heap fetches an index-only scan will cost.
Making index-only scans work for you
An index-only scan is only as good as the VM coverage of the table. These points decide whether you get the benefit:
- Mostly static tables benefit most. Append-only and rarely updated tables keep nearly all pages all-visible. Hot, frequently updated tables rarely do, and an index-only scan on them can be no better than an ordinary index scan.
- Autovacuum must run. For tables that are updated, autovacuum sets the bits as a side effect of cleaning. For insert-only tables, PostgreSQL 13 and later also trigger autovacuum from insert counts (
autovacuum_vacuum_insert_thresholdandautovacuum_vacuum_insert_scale_factor). Earlier versions could leave a freshly loaded table with no bits set for a long time. - Long transactions block the bits. VACUUM can only mark a page all-visible if every tuple on it is older than the oldest running snapshot. A session with an old
backend_xmin(see the earlier chapter on the xmin horizon) keeps recently changed pages from qualifying, even though VACUUM runs. - Covering indexes extend the idea.
INCLUDEadds payload columns to a B-tree without making them part of the search key:
CREATE INDEX events_user_cover_idx
ON events (user_id) INCLUDE (payload);A query that selects user_id and payload and filters on user_id can now use an index-only scan. The cost is a larger index and more write work on every update to those columns.
- Wide values reduce the benefit. Including large columns makes the index bigger. That can cost more in cache misses than the saved heap visits return.
The all-frozen bit and vacuum itself
The VM also helps VACUUM. A normal VACUUM skips pages whose all-visible bit is set, since they hold no dead tuples. A vacuum that must advance the oldest unfrozen transaction ID (an aggressive vacuum) can skip pages whose all-frozen bit is set, because their tuples never need freezing again. This is why a large, mostly cold table can be vacuumed quickly. It reads only the pages that changed since last time.
Common mistakes
- Expecting
Index Only Scanto guarantee no heap access. OnlyHeap Fetches: 0shows that. - Benchmarking right after a bulk load without running VACUUM first. The bits are not set yet, so the result is pessimistic.
- Selecting
*, or one extra column outside the index, and then wondering why the planner picks a different plan. - Treating a rising
Heap Fetchesfigure as an index problem. It is usually a vacuum or long-transaction problem.
Exercise
A reporting query SELECT order_id FROM orders WHERE order_id BETWEEN 1000 AND 9000 uses an Index Only Scan on the primary key, but EXPLAIN ANALYZE shows Heap Fetches: 7,800 out of about 8,000 rows. The table receives heavy updates, and autovacuum is enabled. Give two possible causes and a query to check one of them.
Show answer
Likely causes: (1) the pages holding those rows were modified recently and autovacuum has not revisited them yet, so their all-visible bits are clear; (2) a long-running transaction holds back the xmin horizon, so VACUUM cannot mark recently changed pages all-visible even when it runs. To check the second, run SELECT pid, state, xact_start, backend_xmin FROM pg_stat_activity WHERE backend_xmin IS NOT NULL ORDER BY age(backend_xmin) DESC; and look for old transactions. You can also compare all_visible from pg_visibility_map_summary('orders') with relpages in pg_class.
Exercise
Why does an UPDATE clear a page's all-visible bit, while only VACUUM can set it?
Show answer
An UPDATE creates a new tuple version and sets xmax on the old one. Neither version is yet known to be visible to every snapshot, so the "all-visible" guarantee is broken, and clearing the bit is cheap and must happen at once to keep index-only scans correct. Setting the bit requires proving that every tuple on the page is visible to all snapshots, including the oldest running one. That check needs a full page scan, which is what VACUUM does.