when postgres uses an index
slide the selectivity and watch the plan flip. random reads lose past a few percent.
- address
- everything.indexes.index_or_scan
- part
- part 8, indexes, from the outside
- chapter
- chapter 2 of 12
- reading time
- 10 min
an index makes a query faster when the query wants a few rows. when it wants a lot of them, reading the whole table front to back is cheaper. postgres picks between a seq scan, a bitmap scan and an index scan by estimated cost, and the number that decides it is selectivity: the fraction of rows that match.
on the table below, a plain index scan stops paying off at about 1% of the rows.
the picture
you know how you add an index, run the query, and postgres ignores it? it isn't broken. it did the arithmetic and the index lost.
think of a cookbook with an index at the back. you want every recipe with saffron: three of them, so you look up saffron and flip to three pages. now you want every recipe with salt. that's half the book, and flipping to the back, then to page 212, then back, then page 37, takes far longer than reading the book cover to cover and marking the salty ones as you go (a seq scan).
slide the selectivity. the table has 30,000 rows on 546 pages, and every point is a real plan from the postgres on this page.
300 rows, 1%. still a bitmap scan. a plain index scan would now cost more than reading the whole table. bitmap scan: 302 pages touched, against 546 for reading the whole table.
three things to notice on the scattered column:
- the index scan's page count grows with the rows. it fetches one heap page per matching row: 302 pages for 300 rows, 15,042 for 15,000. the table only has 546.
- the seq scan never changes. 546 pages, whether one row matches or all of them.
- the bitmap scan sits in between. it never reads a page twice, so it tops out at the size of the table, plus a few index pages.
the table
the figure's table is built right here. 30,000 rows is the most ANALYZE reads in full (the statistics are exact, so the plans come out the same on every run). k is 0 to 29,999 shuffled, so k < 300 matches exactly 300 rows, scattered all over the file. k_sorted holds the same numbers in table order.
CREATE TABLE t (id int PRIMARY KEY, k int NOT NULL, k_sorted int NOT NULL, pad text NOT NULL);
INSERT INTO t
SELECT i, (i * 7919) % 30000, i - 1, repeat('x', 100)
FROM generate_series(1, 30000) AS i
ORDER BY i;
CREATE INDEX t_k ON t (k);
CREATE INDEX t_k_sorted ON t (k_sorted);
VACUUM ANALYZE t;
SELECT pg_relation_size('t') / 8192 AS pages, pg_relation_size('t_k') / 8192 AS index_pages;| pagesint8 | index_pagesint8 |
|---|---|
| 546 | 84 |
the pad column is there to make rows a realistic size, about 55 to a page.
three ways to read a table
- seq scan: read every page in order and test every row. the cost doesn't depend on how many rows match.
- index scan: walk the index to the first matching key, then for each entry, fetch the heap page its address points to. one page fetch per row, in key order.
- bitmap scan: walk the index first and only collect addresses, into a bitmap of pages. then read those pages in page order, each one once (a Bitmap Index Scan feeding a Bitmap Heap Scan).
the difference between the last two is the order. here are the 30 rows with k < 30, and the page each one lives on:
the index hands out addresses in key order, and key order has nothing to do with where the rows live. on a disk, each of these jumps is a seek.
k < 30 and their heap pages, on a strip of the table's 546 pages. in index order the scan jumps across the whole file, back and forth. the bitmap scan sorts the same addresses by page first, and sweeps forward.on a spinning disk every one of those jumps is a seek. on an SSD a jump is cheap but still not free, and either way the index scan fetches a page once per row, even when it already fetched that page a moment ago. seq, index and bitmap scans has the machinery (the lossy bitmap, Recheck Cond, prefetching).
where it flips
the planner doesn't run all three. it estimates each one in made-up cost units and keeps the cheapest. at 1%, the bitmap scan wins:
EXPLAIN SELECT * FROM t WHERE k < 300;turn bitmap scans off and you see the next-best plan. not the index scan: the seq scan. the index scan's estimate has crossed the cost of reading everything:
SET enable_bitmapscan = off;
EXPLAIN SELECT * FROM t WHERE k < 300;
SET enable_seqscan = off;
EXPLAIN SELECT * FROM t WHERE k < 300;
RESET enable_bitmapscan;
RESET enable_seqscan;the seq scan's 921.00 is easy to check by hand, from the table's size in pg_class and three settings:
SELECT relpages AS pages, reltuples::int AS rows,
relpages * current_setting('seq_page_cost')::numeric AS page_cost,
reltuples::int * current_setting('cpu_tuple_cost')::numeric AS row_cost,
reltuples::int * current_setting('cpu_operator_cost')::numeric AS filter_cost
FROM pg_class WHERE relname = 't';| pagesint4 | rowsint4 | page_costnumeric | row_costnumeric | filter_costnumeric |
|---|---|---|---|---|
| 546 | 30000 | 546 | 300.00 | 75.0000 |
seq_page_cost 1.0, every row at cpu_tuple_cost 0.01, and one k < 300 test per row at cpu_operator_cost 0.0025. they add up to the 921 EXPLAIN printed. none of them depends on how many rows match.the index scan's 953.54 is mostly 300 heap fetches at random_page_cost 4, each one a page the planner assumes is out of order. the cost model prices both by hand, including the bit of the index scan's arithmetic that guesses how many of those fetches hit pages already in cache.
EXPLAIN SELECT * FROM t WHERE k < 1500;the crossover is a guess
a rule like "an index helps below 5%" can't be right in general, because the crossover depends on things the rule doesn't mention.
where the rows live. flip the figure to k_sorted: the index scan wins at every point, all the way to half the table. matching rows sit next to each other, so consecutive index entries point into the same page, and 15,000 rows cost 315 page reads. the planner knows this from the column's correlation in pg_stats: close to 1 or -1 means table order follows the column. an append-only table and its timestamp column is the everyday case.
what a random read costs. random_page_cost defaults to 4: the planner prices a page fetched out of order at four sequential ones. the manual explains the 4 this way: a random read from storage really costs far more than four sequential ones, but most random reads are expected to be served from cache. on SSDs, or a database that fits in memory, a random read is close to a sequential one, and lowering it (1.1 is a common pick) makes the planner use indexes for bigger results. here's the 50% point both ways:
EXPLAIN SELECT * FROM t WHERE k < 15000;
SET random_page_cost = 1.1;
EXPLAIN SELECT * FROM t WHERE k < 15000;
RESET random_page_cost;seq scan at 4, bitmap scan at 1.1. switch the figure to 1.1 to see the costs move. it's a statement about your hardware, so set it per tablespace or server after measuring, not per query to win one plan (steering the planner).
tiny tables
below a few pages, nothing beats reading the table. products is 5 pages. here's a lookup by its primary key, the most index-friendly query there is:
EXPLAIN SELECT name FROM products WHERE id = 200;a seq scan. reading 5 pages and checking 200 rows is cheaper, in the planner's units, than descending an index and then fetching the page anyway. the left-handed teapot comes back either way. this is also why index experiments on small tables mislead: build the table big enough first, as above.
keylines
- selectivity decides it: few rows, index; most rows, seq scan; in between, a bitmap scan.
- an index scan fetches one heap page per row, in key order. that's what loses past a few percent.
- a bitmap scan sorts the addresses first, so each page is read once, in order.
- the crossover moves with correlation and random_page_cost. measure, don't memorize a percentage.
- the planner prices disk reads even when everything is cached.