Part 16 / Topic 3 of 5
Scan types
How Postgres gets rows out of one table — four shapes, one story each. Give the planner an index and re-ask:
CREATE INDEX idx_big_orders_customer ON big_orders (customer_id);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders WHERE customer_id = 42;
CREATE INDEX
QUERY PLAN
-----------------------------------------------------------------------------
Bitmap Heap Scan on big_orders (actual rows=40 loops=1)
Recheck Cond: (customer_id = 42)
Heap Blocks: exact=40
-> Bitmap Index Scan on idx_big_orders_customer (actual rows=40 loops=1)
Index Cond: (customer_id = 42)
(5 rows)
The Seq Scan became a two-node team — and the four shapes line up:
- Seq Scan — read every page start to finish. Optimal for most-of-the-table queries (sequential I/O is cheap); a smell only when paired with huge
Rows Removed. - Index Scan — walk the index, hop to the heap per row. Ideal for a handful of rows; the hopping (random I/O) gets expensive as matches grow.
- Bitmap Index/Heap Scan — the compromise you're looking at above: collect all matching locations from the index first (
Bitmap Index Scan), sort them by page, then visit each heap page once (Bitmap Heap Scan,Heap Blocks: exact=40). The planner's pick for "more than a few, less than most". - Index Only Scan — the index alone answers the query, no heap at all. Ask for just the indexed column (after a VACUUM has freshened Part 15's visibility map):
VACUUM big_orders;
EXPLAIN (COSTS OFF) SELECT customer_id FROM big_orders WHERE customer_id = 42;
VACUUM
QUERY PLAN
-------------------------------------------------------------
Index Only Scan using idx_big_orders_customer on big_orders
Index Cond: (customer_id = 42)
(2 rows)
None of these is "best" — each wins its own selectivity range, and the planner moves between them as estimates change. Your job is recognising which was chosen and whether the reason (the row estimate) was sane.
🧪 Quick quiz — answer from memory, then check.
- Why does a bitmap scan exist between index scan and seq scan?
- What two things does an Index Only Scan require?
Show the answers
- It batches index matches and visits each heap page once, in order — index precision without per-row random hops.
- Every needed column in the index, and visibility information fresh enough (VACUUM) to skip heap checks.
Done here? The practice set for Part 16 — 4 exercises with solutions — is on the part page.