Sub topic 2
Reading EXPLAIN (ANALYZE, BUFFERS) and Heap Fetches
This chapter assumes you know basic SQL, what a B-tree index is at a high level, and how to run EXPLAIN. The examples use the orders table from earlier in the tutorial.
Reading the plan
EXPLAIN (ANALYZE, BUFFERS) runs the query and reports what the planner chose and what actually happened.
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;Look for these parts of the output:
| Plan line | What it means |
|---|---|
| Index Scan | Reads the index, then fetches each matching row from the table heap |
| Index Only Scan | Answers from the index and visits the heap only when needed |
| Heap Fetches: 0 | The index-only scan avoided the heap for every row |
| Heap Fetches: N (N > 0) | N rows needed a heap visit, so the scan is only partly effective |
Designing a covering index
A covering index contains every column the query reads. With an index on customer_id alone, the query still needs total, so PostgreSQL must visit the heap.
Adding payload columns with INCLUDE
The INCLUDE clause stores extra columns in the index entries without making them search keys.
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;Put columns you filter or sort on in the key. Put columns you only return in INCLUDE.
> Warning: Heap Fetches rises after many updates. Run VACUUM to restore the all-visible bits.
Exercise
Which index lets the query SELECT customer_id, total FROM orders WHERE customer_id = 42; run as an Index Only Scan, and what should Heap Fetches show after VACUUM?
Show answer
Use CREATE INDEX orders_customer_total_idx ON orders (customer_id) INCLUDE (total);, run VACUUM (ANALYZE) on orders, and expect Heap Fetches to be 0 or near 0.