Sub topic 3
What an index-only scan is and what it needs
An index-only scan answers a query using only the index, without reading the table's heap pages. This chapter explains the conditions that make one possible and how to recognize one in a plan. It assumes you can read a simple EXPLAIN plan and know that a B-tree index stores sorted key values with pointers to table rows. The chapters on the visibility map, VACUUM and Heap Fetches cover the details this chapter only introduces.
The idea
An ordinary Index Scan has two steps for every matching row:
- Search the index to find the entry for the key.
- Follow the entry's tuple pointer (a block number and an offset, called the TID) into the heap to fetch the row.
Step 2 is often the expensive part. Matching rows can be scattered across many heap pages, so each lookup may cost a random page read.
If the index entry already holds every value the query needs, step 2 has no purpose. An index-only scan stops after step 1 and returns values straight from the index entry. The result is fewer page reads and less cache pressure.
There is one catch. PostgreSQL uses MVCC (multiversion concurrency control), so the heap can contain several versions of a row. Each version is visible to some transactions and invisible to others. The index entry does not record this visibility information. The planner therefore needs another way to know that an index entry is visible to your query without checking the heap. That mechanism is the visibility map.
The three requirements
An index-only scan needs all three of the following.
- The index type can return column values. B-tree indexes always can. Some GiST and SP-GiST operator classes can. GIN, hash and BRIN indexes cannot. The last chapter of this tutorial covers this requirement in detail.
- Every column the query references is stored in the index. This includes the select list, the
WHEREclause,ORDER BY,GROUP BYand join conditions. If one column is missing from the index, the planner cannot use an index-only scan for that table. - The heap pages involved are marked all-visible. The visibility map has one bit per heap page. When the bit is set, every row on that page is visible to every transaction. For those pages the scan skips the heap. For pages whose bit is not set, the scan must still visit the heap to check visibility. Those visits are the
Heap Fetchesyou will see inEXPLAIN (ANALYZE).
The first two requirements decide whether the planner can choose an index-only scan. The third decides how much the scan actually saves at run time.
Setting up the example
The examples use a one-million-row orders table.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id integer NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
note text
);
INSERT INTO orders (customer_id, status, total, created_at)
SELECT (random() * 10000)::int,
(ARRAY['new','paid','shipped','cancelled'])[1 + (random() * 3)::int],
(random() * 500)::numeric(10,2),
now() - random() * interval '365 days'
FROM generate_series(1, 1000000);The table has about 10,000 distinct customers, so a lookup by customer_id returns roughly 100 rows.
A query that is not covered
Create a plain index on customer_id. Run VACUUM (ANALYZE) so the planner has fresh statistics and the visibility map is populated.
CREATE INDEX orders_customer_idx ON orders (customer_id);
VACUUM (ANALYZE) orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;The query needs total, and the index stores only customer_id. Requirement 2 fails. Expect an Index Scan or a Bitmap Heap Scan on orders. The plan will look roughly like this, though the numbers will differ on your machine:
Bitmap Heap Scan on orders (cost=5.20..380.10 rows=100 width=10)
(actual time=0.09..0.35 rows=98 loops=1)
Recheck Cond: (customer_id = 42)
Heap Blocks: exact=96
Buffers: shared hit=99
-> Bitmap Index Scan on orders_customer_idx ...The Heap Blocks line shows the scan visiting about as many heap pages as there are matching rows, because the rows are scattered through the table.
A query that the index can cover
Now ask only for a column that the index already holds:
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id FROM orders WHERE customer_id = 42;Every referenced column, customer_id in both the select list and the WHERE clause, is in the index. The planner can choose an Index Only Scan. The same applies to SELECT count(*) FROM orders WHERE customer_id = 42. That query needs no column values from the heap, only the number of visible rows.
For the original query, which also needs total, you can add total to the index. The INCLUDE clause does this without making total a search key:
CREATE INDEX orders_customer_total_idx
ON orders (customer_id) INCLUDE (total);
VACUUM (ANALYZE) orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;The planner can now use the new index, and the plan should look like this:
Index Only Scan using orders_customer_total_idx on orders
(cost=0.42..4.50 rows=100 width=10) (actual time=0.03..0.06 rows=98 loops=1)
Index Cond: (customer_id = 42)
Heap Fetches: 0
Buffers: shared hit=4Heap Fetches: 0 means the visibility map covered every page involved, so the scan never touched the heap. The buffer count dropped from about a hundred to a handful. Later chapters cover INCLUDE itself, the choice between key and included columns, and the cost of the extra index size.
Index-only is a plan choice, not a guarantee
Two things are easy to get wrong about this feature.
The planner chooses on cost. A covering index makes an index-only scan possible, but the planner uses it only when it estimates the scan to be cheapest. It estimates the fraction of heap pages that are all-visible from pg_class.relallvisible. A table with few all-visible pages makes an index-only scan look no better than an ordinary index scan, so the planner may skip it. On a small table, a sequential scan may be cheaper still.
The plan label does not show the savings. A plan can say Index Only Scan and still fetch from the heap for most rows. Always read the Heap Fetches line. The label shows that the planner chose the scan type. The Heap Fetches count shows how well the scan avoided the heap.
What counts as "every referenced column"
The rule covers the entire query, not only the select list. Consider these three variations, assuming only orders_customer_total_idx exists:
| Query | Index-only possible? | Reason |
|---|---|---|
| `SELECT total FROM orders WHERE customer_id = 42` | Yes | `customer_id` and `total` are both in the index |
| `SELECT total FROM orders WHERE customer_id = 42 AND status = 'paid'` | No | `status` appears in the `WHERE` clause but is not in the index |
| `SELECT * FROM orders WHERE customer_id = 42` | No | `*` expands to every column, including `note` and `created_at` |
The second row is a common surprise. A column you only filter on still has to be available in the index. The filter can be evaluated only if the executor can read the value, and in this index status is neither a key nor a payload column. The third row shows why SELECT * seldom suits index-only scans.
Checking your understanding quickly
When a query you expect to be index-only is not, work through these checks in order:
- Does the index contain every column the query references?
- Does the index type support returning values?
- Has
VACUUMrun recently enough that most heap pages are all-visible? - Does the planner think the index-only scan is cheaper than the alternatives? Check
ANALYZEfreshness and the table's size.
The troubleshooting chapter develops this list. For now, remember that requirements 1 and 2 determine whether an index-only scan is possible, and requirement 3 determines whether it pays off.
Exercise
The table has only the index orderscustomertotalidx (customerid, with total included). For each query, say whether an Index Only Scan is possible and why: (a) SELECT count(*) FROM orders WHERE customerid = 7; (b) SELECT total FROM orders WHERE customerid = 7 ORDER BY createdat; (c) SELECT customerid, total FROM orders WHERE customer_id = 7, where EXPLAIN (ANALYZE) shows an Index Only Scan with Heap Fetches: 95 for 100 returned rows. In case (c), what does the large Heap Fetches count tell you?
Show answer
(a) Yes. The query needs no column values beyond customerid, which is in the index, and counting rows needs only visibility. (b) No. ORDER BY createdat references a column that is not in the index, so the planner cannot use an index-only scan. (c) The plan is index-only in shape, but the visibility map is not marking most of the relevant heap pages all-visible, so the scan went to the heap for nearly every row (95 of 100). The scan type is correct, but it saves almost nothing. The pages probably have recent updates or inserts that VACUUM has not processed yet.