// troubleshooting guide

Heap fetches in an index-only scan

A PostgreSQL index-only scan that reports thousands of heap fetches is reading the table after all. Why the visibility map decides that, how to measure it, and how to keep the map current with VACUUM and autovacuum settings.

Covers PostgreSQL

The symptom

Вот Index Only Scan is supposed to answer the query from the index without touching the table. PostgreSQL can only do that for rows on pages it knows are visible to every transaction, and that knowledge lives in the table's visibility map, not in the index. For every row on a page that is not marked all-visible, the scan goes to the table to check the row. The plan counts those visits as Heap Fetches.

С Heap Fetches: 0 the scan is as cheap as it looks. With a heap fetch for most rows it is an ordinary index scan with a better name. The query plan viewer flags the second case. The examples use a shop schema with 400,000 orders, 40,000 of them for customer 1.

Diagnose it

Read Heap Fetches next to the row count

Right after a VACUUM, a covering index gives a clean index-only scan:

CREATE INDEX orders_customer_total_idx ON orders (customer_id) INCLUDE (total);

EXPLAIN (ANALYZE, BUFFERS)
SELECT sum(total) FROM orders WHERE customer_id = 1;
->  Index Only Scan using orders_customer_total_idx on orders  (cost=0.42..1331.42 rows=40400 width=6) (actual time=1.294..4.364 rows=40000.00 loops=1)
      Heap Fetches: 0
      Buffers: shared hit=1 read=156

Now change some of those rows. An update writes a new row version, and the pages it touches lose their all-visible mark:

UPDATE orders SET status = status WHERE customer_id = 1 AND order_id % 2 = 0;

EXPLAIN (ANALYZE, BUFFERS)
SELECT sum(total) FROM orders WHERE customer_id = 1;
Buffers: shared hit=3691
->  Index Only Scan using orders_customer_total_idx on orders  (cost=0.42..1403.42 rows=40400 width=6) (actual time=0.018..8.406 rows=40000.00 loops=1)
      Heap Fetches: 60101
      Buffers: shared hit=3691

Сравнить Heap Fetches с rows the scan returned, and the Buffers line with the one before: 3,691 pages instead of 157. The node is still called Index Only Scan, but it now visits the table for every row on a page the update touched. The count is higher than the 40,000 rows returned because the index still points at the 20,000 old row versions, and each of those costs a visit too.

Check the visibility map

pg_class stores how many of the table's pages were all-visible at the last VACUUM или ANALYZE. The planner uses that number to decide whether an index-only scan is worth choosing:

ANALYZE orders;

SELECT relpages, relallvisible,
       round(100.0 * relallvisible / relpages, 1) AS pct_all_visible
FROM pg_class
WHERE oid = 'orders'::regclass;
relpages | relallvisible | pct_all_visible
    4482 |          1119 |            25.0

Этот pg_visibility extension reads the map itself, so the answer is current:

CREATE EXTENSION IF NOT EXISTS pg_visibility;

SELECT * FROM pg_visibility_map_summary('orders');
all_visible | all_frozen
       1119 |          0

See when the table was last vacuumed

SELECT relname, n_live_tup, n_dead_tup, last_vacuum, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'orders';

Many dead tuples and an old or empty last_autovacuum mean autovacuum has not reached the table since the rows changed. The autovacuum status snippet runs the same check for every table.

Fix it

Vacuum the table

VACUUM removes the dead row versions and marks the pages all-visible again. It does not block reads or writes.

VACUUM orders;

EXPLAIN (ANALYZE, BUFFERS)
SELECT sum(total) FROM orders WHERE customer_id = 1;
Buffers: shared hit=328
->  Index Only Scan using orders_customer_total_idx on orders  (cost=0.42..1359.68 rows=38129 width=6) (actual time=0.006..1.807 rows=40000.00 loops=1)
      Heap Fetches: 0
      Buffers: shared hit=328

Простые VACUUM is enough. VACUUM FULL rewrites the table under an exclusive lock and is not needed for this.

Make autovacuum reach the table sooner

Autovacuum starts on a table when the dead rows exceed a fraction of the table, 20% by default. On a large table that is a long wait. Lower the fraction for the tables your index-only scans depend on:

ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.02);

A table that only receives inserts has no dead rows to trigger on. For those, autovacuum uses a separate threshold based on inserted rows, which you can lower the same way:

ALTER TABLE orders SET (autovacuum_vacuum_insert_scale_factor = 0.02);

The server-wide defaults are autovacuum_vacuum_scale_factor and the other autovacuum settings.

Look for a transaction that holds vacuum back

Если VACUUM runs and the heap fetches stay, an old transaction is probably still open. Vacuum cannot mark a page all-visible while any transaction might still need the old row versions on it. VACUUM (VERBOSE) says so in its report, as a count of tuples that are dead but not yet removable. Find the session that holds the oldest snapshot:

SELECT pid, state, age(backend_xmin) AS xmin_age, now() - xact_start AS open_for
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL AND pid <> pg_backend_pid()
ORDER BY age(backend_xmin) DESC;

End that transaction, then vacuum again.

When to leave it alone

A few heap fetches are normal on any table that is being written: the newest pages are never all-visible. Leave the plan alone when the fetches are a small share of the rows, or when the query is fast anyway. On a table where most rows change between vacuums, an index-only scan will never be clean, and the extra columns in the index are not buying anything; a plain index is smaller and does the same job.

The checklist

Work through it in order. Each step gives you the evidence for the next one.

  1. Run EXPLAIN (ANALYZE, BUFFERS) and compare Heap Fetches with the rows the scan returned.
  2. Check relallvisible against relpages in pg_class, or pg_visibility_map_summary.
  3. Look at last_vacuum, last_autovacuum and n_dead_tup in pg_stat_user_tables.
  4. Run VACUUM on the table and capture the plan again.
  5. If nothing changed, find the oldest open transaction in pg_stat_activity.
  6. Lower autovacuum_vacuum_scale_factor for the table so it is vacuumed more often.

Questions that come up

What does Heap Fetches mean in a PostgreSQL plan?

It is the number of rows for which an index-only scan had to read the table to check that the row is visible. The index holds the column values but not the visibility information, so the scan can skip the table only for pages the visibility map marks as all-visible.

Why is my Index Only Scan slow?

Usually because of heap fetches. When most pages are not marked all-visible, the scan visits the table for most rows and costs about as much as an ordinary index scan. Vacuuming the table sets the visibility map and brings the fetch count down.

Does ANALYZE fix heap fetches?

No. ANALYZE refreshes statistics, including the planner's count of all-visible pages, but it does not change the visibility map. Only VACUUM marks pages all-visible.

Why did PostgreSQL stop choosing an index-only scan?

The planner estimates heap fetches from the share of all-visible pages recorded in pg_class. When that share is low it expects an index-only scan to visit the table anyway and may pick a bitmap or plain index scan. After a VACUUM the share rises and the index-only scan comes back.

Do other databases have this problem?

Not in this form. It follows from PostgreSQL keeping row visibility in the table and not in the index. SQL Server, MySQL InnoDB and Oracle covering index reads do not report an equivalent of heap fetches.

// fix it where the query lives

Run these queries in SQLly

SQLly is a native SQL workbench for macOS, Windows and Linux. The query plan viewer and formatter these guides link to are built into its editor.