seq scans, index scans and bitmap scans
three ways to read a table, and the bitmap that turns random reads back into sequential ones.
- address
- everything.execution.scans
- part
- part 9, how a query runs
- chapter
- chapter 7 of 13
- reading time
- 10 min
there are three ways to read a table. a seq scan reads every page, in order. an index scan walks an index and jumps to the table once per matching row. a bitmap scan collects every matching row's address from the index first, sorts them by page, and then reads each page once, in order.
that last one exists to turn the index scan's random reads back into a sequential sweep. and when it runs out of memory, it doesn't spill: it forgets which rows matched and rechecks whole pages.
the picture
you know how postgres sometimes ignores your index, and sometimes uses it in a way EXPLAIN calls "bitmap"? it's choosing between three ways of walking a library.
walk every shelf and look at every book (a seq scan). or look each book up in the catalogue and walk to its shelf, one trip per book, back and forth across the building (an index scan). or look up every book first, write down the shelf numbers, sort the list, and then walk the aisles once, front to back (a bitmap scan).
here are all three, finding the 599 events of users 7, 8 and 9 in the events table, 335 pages:
the index hands over rows by user_id, then by address. so the scan sweeps the table once for user 7, again for 8, again for 9: 448 page visits for 281 different pages, and every one of them is a jump to wherever the next row lives.
an index scan visits 448 pages for 281 different ones, because the index keeps rows in user_id order and the table keeps them in the order they arrived. a b-tree keeps equal keys in address order, so within one user it moves forward; at the next user it jumps back to the start. on a disk that hates seeking, every jump costs, and that's what the bitmap avoids.
what postgres picks
CREATE INDEX ON events (user_id);
CREATE INDEX ON events (kind);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, kind FROM events WHERE user_id BETWEEN 7 AND 9;two nodes. the Bitmap Index Scan walks the index and fills a bitmap with one entry per matching row, without touching the table. the Bitmap Heap Scan above it then reads the table in page order (Heap Blocks: exact=281) and rechecks the condition on each row it finds (Recheck Cond). the price of the bitmap: rows come out in table order, not index order, so it can't hand an ORDER BY its sort for free. now all three, side by side:
- 1EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 2SELECT id, kind FROM events WHERE user_id BETWEEN 7 AND 9
- Bitmap Heap Scan on events (actual rows=599.00 loops=1)
- Recheck Cond: ((user_id >= 7) AND (user_id <= 9))
- Heap Blocks: exact=281
- Buffers: shared hit=282 read=1
- -> Bitmap Index Scan on events_user_id_idx (actual rows=599.00 loops=1)
- Index Cond: ((user_id >= 7) AND (user_id <= 9))
- Index Searches: 1
- Buffers: shared hit=1 read=1
the planner's choice for three users' events: a bitmap scan.
450 for the index scan: the 448 heap visits from the first figure, plus 2 index pages. 283 for the bitmap: 281 heap pages and 2 index pages. 335 for the seq scan, which tests all 25,000 rows to keep 599 (Rows Removed by Filter: 24401). here the bitmap wins. ask for a single row and the index scan wins; ask for a third of the table and the seq scan does. where those lines cross, and how the planner knows, is when postgres uses an index.
index only scans
if every column the query needs is in the index, postgres can skip the table altogether... almost. an index entry doesn't know whether its row version is visible to you; only the table's row header does. so an Index Only Scan checks the visibility map first: a page marked all-visible means every row on it is visible to everyone, and the table can be skipped. otherwise it fetches the row anyway, and counts it:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM events WHERE user_id BETWEEN 7 AND 9;
UPDATE events SET amount = amount WHERE user_id = 8;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM events WHERE user_id BETWEEN 7 AND 9;
VACUUM events;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM events WHERE user_id BETWEEN 7 AND 9;Heap Fetches: 0, 3 pages. then an UPDATE touches user 8's rows, which clears the all-visible bit of every page they're on, and the same scan does 500 heap fetches and 258 page accesses. VACUUM sets the bits again, and it's back to 0. the details, and INCLUDE columns, are index-only scans.
combining indexes
two conditions on two indexed columns don't need a two-column index. each index builds its own bitmap, and the bitmaps are combined, bit by bit, before the table is touched:
- 1EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 2SELECT id FROM events WHERE kind = 'signup' AND user_id BETWEEN 7 AND 30
- Bitmap Heap Scan on events (actual rows=24.00 loops=1)
- Recheck Cond: ((kind = 'signup'::text) AND (user_id >= 7) AND (user_id <= 30))
- Heap Blocks: exact=10
- Buffers: shared hit=12 read=5
- -> BitmapAnd (actual rows=0.00 loops=1)
- Buffers: shared hit=2 read=5
- -> Bitmap Index Scan on events_kind_idx (actual rows=500.00 loops=1)
- Index Cond: (kind = 'signup'::text)
- Index Searches: 1
- Buffers: shared read=2
- -> Bitmap Index Scan on events_user_id_idx (actual rows=3331.00 loops=1)
- Index Cond: ((user_id >= 7) AND (user_id <= 30))
- Index Searches: 1
- Buffers: shared hit=2 read=3
two conditions, two indexes, one bitmap each, ANDed before the heap is touched.
a BitmapAnd keeps the rows both bitmaps have; a BitmapOr keeps rows either has, and it's how postgres answers an OR across two different columns with indexes at all. a plain index scan can only follow one index.
when the bitmap doesn't fit
the bitmap lives in memory, and it gets work_mem, 4MB by default. one entry per page with a bit per row on it. on a big table with matches on most pages, that runs out. postgres doesn't spill the bitmap to disk. it makes it lossy: some pages stop remembering which rows matched and just say "something on this page matched".
SET work_mem = '64kB';
EXPLAIN ANALYZE
SELECT sum(value) FROM readings WHERE sensor = 7;
-- 1,500 matching rows spread over 1,728 pages- 1EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 2SELECT sum(value) FROM readings WHERE sensor = 7
- Aggregate (actual rows=1.00 loops=1)
- Buffers: shared hit=1500 read=3
- -> Bitmap Heap Scan on readings (actual rows=1500.00 loops=1)
- Recheck Cond: (sensor = 7)
- Heap Blocks: exact=1500
- Buffers: shared hit=1500 read=3
- -> Bitmap Index Scan on readings_sensor_idx (actual rows=1500.00 loops=1)
- Index Cond: (sensor = 7)
- Index Searches: 1
- Buffers: shared read=3
the default work_mem, 4MB: the bitmap remembers every matching row.
run it:
CREATE TABLE readings AS
SELECT g AS id, g % 20 AS sensor, (g * 7919) % 1000 AS value, repeat('x', 400) AS note
FROM generate_series(1, 30000) AS g
ORDER BY g;
CREATE INDEX ON readings (sensor);
VACUUM ANALYZE readings;
SET work_mem = '64kB';
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT sum(value) FROM readings WHERE sensor = 7;the answer is the same either way: the recheck is what keeps a lossy bitmap correct. it just costs CPU, for rows that were never going to match.
the seq scan is not the villain
the seq scan reads every page, but it reads them in order, which is the cheapest way to read anything: the OS reads ahead, and since postgres 18 so can postgres itself (asynchronous I/O). a big seq scan also goes through a small ring buffer, so it doesn't flush everyone else's pages out of the cache. and it's the one scan that can be split between several processes (parallel query).
keylines
- seq scan: every page, in order. cheap per page, and nothing to look up.
- index scan: follows the index, so it returns sorted rows but jumps around the table.
- bitmap scan: addresses first, sorted by page, then one sweep. no order, but no revisits.
- bitmaps combine: BitmapAnd and BitmapOr use two indexes for one query.
- out of work_mem, a bitmap goes lossy (whole pages, rechecked), never to disk.