Sub topic 11
Troubleshooting: when the planner does not pick an index-only scan
This chapter assumes you can read EXPLAIN (ANALYZE, BUFFERS) output. It also assumes you know what the visibility map is, what VACUUM does to it, and how INCLUDE adds payload columns to an index. Everything here uses the orders table from earlier chapters.
You built a covering index and ran the query, but the plan shows an Index Scan, a Bitmap Heap Scan, or a Seq Scan. There are two different failures to tell apart:
- The planner did not choose an Index Only Scan node. The cause is the query, the index, or the cost estimates.
- The planner chose an Index Only Scan node, but it still visits the heap. The cause is the visibility map, and you see it as a high
Heap Fetchescount.
Settle which failure you have before changing anything.
A diagnostic order
Work from the cheapest check to the most expensive.
Cause 1: the query needs a column the index does not have
An index-only scan is possible only if every column the query references is available from the index. "Referenced" covers the whole statement: the SELECT list, WHERE, ORDER BY, GROUP BY, JOIN conditions, and expressions in any of them.
The most common culprit is SELECT *. With orders_customer_total_idx (key customer_id, payload total), these two queries behave differently:
-- Can be an Index Only Scan: both columns are in the index.
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;
-- Cannot: status, created_at and note are not in the index.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;The second query gets an Index Scan or Bitmap Heap Scan, because the executor has to read the heap for the other columns. A filter such as WHERE customer_id = 42 AND status = 'paid' causes the same problem. The planner counts status as a needed column even though it never appears in the output.
Fix it by naming only the columns you need. If the query really needs one more column, add it with INCLUDE and weigh the size cost covered in the previous chapter.
Expression indexes have a related trap. An index on lower(email) stores the computed value, not email. The planner generally decides what is needed by looking at the underlying column, so a query on lower(email) often cannot use an index-only scan unless email is also an index column. Check the plan on your PostgreSQL version instead of assuming.
Cause 2: the index type cannot return column values
B-tree indexes always support index-only scans. Hash and BRIN indexes do not, because they cannot return the original column values. GiST and SP-GiST support them only for some operator classes. GIN does not support them. If your covering index is not a B-tree, check this first. The access-method chapter covers the details.
Cause 3: the planner thinks a heap-free scan will not pay off
The planner picks the cheapest plan by estimated cost. An index-only scan is just one candidate, and it loses in several legitimate situations.
- Many rows match. Reading 40% of a table through an index, even a covering one, can cost more than one sequential pass. Try
WHERE customer_id < 5000on the one-million-row table and you will probably see a Seq Scan. - The table is small. A few pages are cheaper to scan than to navigate through an index.
- The visibility map looks empty. The cost model uses
pg_class.relallvisibleto estimate how many heap fetches an index-only scan will need. If that number is low, the scan is costed like an ordinary Index Scan, and another plan can win. - Statistics are stale. Wrong row estimates push the plan toward the wrong node type.
Check the visibility map statistics:
SELECT relname, relpages, relallvisible
FROM pg_class
WHERE relname = 'orders';If relallvisible is far below relpages, run VACUUM (ANALYZE) orders; and re-test. A freshly bulk-loaded table is the usual case. Since PostgreSQL 13 autovacuum also triggers on inserts, but it can take a while to reach a new table, so run the vacuum yourself when testing.
To find out whether the planner could use the index-only scan at all, you can discourage the alternatives for one transaction:
BEGIN;
SET LOCAL enable_seqscan = off;
SET LOCAL enable_bitmapscan = off;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;
ROLLBACK;If an Index Only Scan appears now, the index and query are fine and the choice came down to cost. Compare the actual times of both plans. If the forced plan is not faster, the planner was right. If it is faster, look at statistics (ANALYZE, a higher statistics target) and at cost settings such as random_page_cost.
Cause 4: Heap Fetches stays high
Now suppose the plan does show Index Only Scan, but Heap Fetches is a large share of the rows returned. The scan is paying for index and heap access both. Each heap fetch happens because the page holding that row is not marked all-visible.
First, compare against a baseline. Run the query, then VACUUM orders;, then run it again. If Heap Fetches drops sharply, the visibility map was just stale. Updates and deletes clear all-visible bits on the pages they touch, so a write-heavy table needs frequent vacuuming for this to work. You can tune autovacuum for that table, for example with a lower autovacuum_vacuum_scale_factor.
If Heap Fetches stays high after a manual VACUUM, something is stopping vacuum from marking pages. A page can be marked all-visible only when every tuple on it is visible to every current and future snapshot. An old snapshot prevents that. Look for these:
-- Long-running or idle-in-transaction sessions
SELECT pid, state, xact_start, age(backend_xmin) AS xmin_age
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC;
-- Replication slots that hold back the horizon
SELECT slot_name, active, xmin, catalog_xmin
FROM pg_replication_slots;
-- Forgotten prepared transactions
SELECT gid, prepared, owner FROM pg_prepared_xacts;A session left idle in transaction, an abandoned replication slot, or a stuck prepared transaction can each keep the cleanup horizon back for hours. Vacuum then cannot mark recently changed pages all-visible, and index-only scans quietly degrade. Fixing the blocker, not vacuuming harder, solves it.
Heap fetches are also expected when you query data that was just written. Rows inserted after the last vacuum live on pages that are not yet all-visible. A table that is mostly appended to and queried by its newest rows will always show some fetches.
Quick reference
| Symptom in the plan | Likely cause | First check | Fix |
|---|---|---|---|
| Index Scan or Bitmap Heap Scan, no Index Only Scan | A referenced column is missing from the index | List every column used in `SELECT`, `WHERE`, `ORDER BY` | Narrow the query or add `INCLUDE` columns |
| Seq Scan despite a covering index | Many rows match, or the table is small | Estimated rows versus table size | Usually none, the plan is correct |
| Index Only Scan chosen only when forced | Low `relallvisible` or bad statistics | `pg_class.relallvisible`, `ANALYZE` | `VACUUM (ANALYZE)`, adjust statistics |
| Index Only Scan with high `Heap Fetches` | Pages are not all-visible | Compare before and after `VACUUM` | Tune autovacuum, remove old snapshots |
| `Heap Fetches` high even after `VACUUM` | An old xmin holds back cleanup | `pg_stat_activity`, slots, prepared transactions | End the idle transaction or drop the slot |
| Non-B-tree index never gives Index Only Scan | The access method cannot return values | Index type | Build a B-tree covering index |
Exercise
A query SELECT customer_id, total FROM orders WHERE customer_id = 42 AND status = 'paid' runs against an index on (customer_id) INCLUDE (total). It gets a Bitmap Heap Scan, even after VACUUM (ANALYZE) orders. Why, and what are two ways to fix it?
Show answer
The status column appears in the WHERE clause but is not in the index, so the executor must read the heap to evaluate it, and an index-only scan is impossible. One fix is to add status to the index, either as INCLUDE (total, status) or as a key column such as (customer_id, status) INCLUDE (total). The other is to create a partial index WHERE status = 'paid', which the query must repeat exactly. A third option is to drop the status filter if the application does not need it.
Exercise
After running a large UPDATE on orders, an Index Only Scan reports Heap Fetches: 9800 for 10,000 rows. You run VACUUM orders; and the count barely changes. Name the diagnostic queries you would run next and what you are looking for.
Show answer
Vacuum cannot mark the pages all-visible, so look for something holding back the cleanup horizon. Query pg_stat_activity for sessions with an old backend_xmin, especially idle in transaction. Query pg_replication_slots for slots with an old xmin or catalog_xmin. Query pg_prepared_xacts for forgotten prepared transactions. End the session, drop the slot, or resolve the prepared transaction, then vacuum again and re-check Heap Fetches.