the cost model
seq_page_cost, random_page_cost, cpu_tuple_cost. price a plan by hand and get the planner's number.
- address
- everything.optimizer.cost_model
- part
- part 10, the optimizer
- chapter
- chapter 1 of 10
- reading time
- 11 min
the planner prices every plan it considers in cost units, where reading one page in order costs 1.0, and keeps the cheapest. the price list is a handful of settings: seq_page_cost, random_page_cost, cpu_tuple_cost and two more. the counts come from pg_class.
there's nothing hidden in it. with the catalog open you can price a scan by hand and land on the planner's number to the cent.
the picture
you know how EXPLAIN says cost=58.97..191.45 and nobody can tell you what a 191 is? it's not milliseconds. it's a price, in a currency postgres made up.
think of a delivery app quoting three routes. the highway is long but you never stop (a seq scan: read every page in order). the back streets are short but every turn costs you (an index scan: jump to exactly the pages you need, out of order). the app doesn't drive any of them. it multiplies distance by a price per kilometre and a price per turn, and shows you the cheapest. change the prices (it's raining, turns are slow now) and a different route wins, even though the roads didn't change.
here's that, for real. one query on orders, three ways to run it, and the three prices that matter most:
bitmap scan wins at 191.45, 16.55 under the seq scan. these are the defaults. change one setting and watch which total moves.
same table, same statistics, same 3,959 estimated rows in every combination. only the prices change, and the winner changes with them. the rest of this chapter takes those three formulas apart.
the price list
SELECT name, setting, short_desc
FROM pg_settings
WHERE name IN ('seq_page_cost', 'random_page_cost', 'cpu_tuple_cost',
'cpu_index_tuple_cost', 'cpu_operator_cost', 'effective_cache_size')
ORDER BY name;| nametext | settingtext | short_desctext |
|---|---|---|
| cpu_index_tuple_cost | 0.005 | |
| cpu_operator_cost | 0.0025 | |
| cpu_tuple_cost | 0.01 | |
| effective_cache_size | 524288 | |
| random_page_cost | 4 | |
| seq_page_cost | 1 |
five prices and one hint:
- seq_page_cost (1.0) is a page read as part of a run, the unit everything else is measured in.
- random_page_cost (4.0) is a page read out of order: an index pointing into the heap, a b-tree descending.
- cpu_tuple_cost (0.01) is handling one row: forming it, passing it up.
- cpu_index_tuple_cost (0.005) is handling one index entry.
- cpu_operator_cost (0.0025) is one call of an operator or function: one
customer_id <= 500test, one comparison during a descent. - effective_cache_size (524288 pages of 8 KB, so 4 GB) isn't a price. it's how much of the database the planner may assume is cached, and it feeds the cache model you'll meet in a minute.
the counts the prices multiply come from the catalog: relpages and reltuples in pg_class, written by VACUUM and ANALYZE, and the row estimate from pg_stats. the planner never touches the table to plan a query.
a seq scan, by hand
reading EXPLAIN already priced one: every page at seq_page_cost, every row at cpu_tuple_cost, and every row through the filter at cpu_operator_cost. for orders that's
CREATE INDEX orders_customer_id ON orders (customer_id);
ANALYZE orders;
SELECT relname, relpages, reltuples
FROM pg_class
WHERE relname IN ('orders', 'orders_pkey', 'orders_customer_id')
ORDER BY relname;| relnamename | relpagesint4 | reltuplesfloat4 |
|---|---|---|
| orders | 83 | 10000 |
| orders_customer_id | 17 | 10000 |
| orders_pkey | 30 | 10000 |
83 × 1.0 + 10,000 × 0.01 + 10,000 × 0.0025 = 208.00, whatever the WHERE says. that's the top line of the dials figure. (the dataset has no secondary indexes, so the block makes one on customer_id.)
an index scan, by hand
now the other end: one order by its primary key.
EXPLAIN SELECT * FROM orders WHERE id = 42;
SELECT level AS height FROM bt_metap('orders_pkey');| heightint8 |
|---|
| 1 |
Index Scan using orders_pkey on orders (cost=0.29..8.30 rows=1 width=33). an index scan pays for two trips: down the b-tree to the right leaf, then over to the heap page the entry points at. both are out-of-order reads. here's the 8.30, piece by piece:
the descent doesn't charge a page read for the root or the inner pages. the planner assumes they're cached, because every lookup goes through them, and charges only a CPU fee per level. the "50 operator costs per level" is a constant in postgres's b-tree cost function, not a setting.
many rows through an index
one row is easy. the interesting case is when the index finds thousands. turn the other two scans off to see what a plain index scan would cost for the dials query:
SET enable_seqscan = off;
SET enable_bitmapscan = off;
EXPLAIN SELECT * FROM orders WHERE customer_id <= 500;
RESET enable_seqscan;
RESET enable_bitmapscan;3,959 estimated rows (that number is estimating rows' job; here we take it as given). the index part scales with the fraction of the index it reads: 3,959 of 10,000 entries is 7 of its 17 leaf pages. the heap part is where it gets clever:
two things decide that heap line.
the cache model. 3,959 index entries point into a table of 83 pages, so most fetches land on a page already fetched. postgres estimates distinct page fetches with a formula from a 1989 paper (Mackert and Lohman): with T pages in the table, N fetches, and a cache bigger than the table (effective_cache_size is 4 GB, the table is 664 KB), it's 2TN / (2T + N), capped at T. here that's 159, capped at 83. so the planner charges the whole table, at random prices.
correlation. if the column were stored in table order, consecutive entries would point into the same page, and those reads would be sequential. postgres interpolates between the random price and the sequential one by correlation squared, from pg_stats. customer_id has a correlation of 0.0009, so it gets the full random price. a timestamp column on an append-only table has a correlation near 1 and gets the cheap one, which is why index-or-scan's sorted column wins everywhere.
one level deeperthe bitmap scan, in between
the bitmap scan's 191.45 uses the same pieces in a different order. it walks the index first (the descent, 7 leaf pages, 3,959 entries, plus 0.1 operator costs per entry for building the bitmap: that's all startup, 58.97, because the bitmap has to be complete before the first heap page is read). then it reads the heap pages in page order, and prices each one between the two page costs:
cost per page = random_page_cost − (random_page_cost − seq_page_cost) × √(pages fetched / pages in table)
the cache model says all 83 pages get fetched, so the square root is 1 and every page costs seq_page_cost. add 3,959 rows at cpu_tuple_cost plus one recheck each at cpu_operator_cost (49.49) and it's 58.97 + 83 + 49.49 = 191.45. that's why the bitmap formula in the figure has a seq_page_cost term and the index formula doesn't.
turning the dials
go back to the figure with those formulas in mind, and each dial does what its formula says:
- random_page_cost only moves the index and bitmap scans. the index scan pays it 90 times (7 + 83 pages), the bitmap scan 7 times. at 1 the index scan wins; at 8 the seq scan does.
- seq_page_cost moves the seq scan and the bitmap scan, both by 83 pages, so on this query it rarely changes the winner. it's the unit, after all: halve it and everything that reads in order gets cheaper together.
- cpu_tuple_cost charges the seq scan for 10,000 rows and the other two for 3,959. raise it and filtering a whole table gets expensive; lower it and reading everything looks free.
SET random_page_cost = 1;
EXPLAIN SELECT * FROM orders WHERE customer_id <= 500;SET random_page_cost = 1;
EXPLAIN SELECT * FROM orders WHERE customer_id <= 500;
RESET random_page_cost;these settings describe hardware, not queries. the defaults date from spinning disks: the manual explains random_page_cost = 4 as a random read being far slower than 4 sequential ones, with most of them expected to hit the cache. on SSDs, or a database that fits in memory, 1.1 is a common setting. set it per server or per tablespace after measuring, never per query to win one plan.
the cheapest path wins
the planner doesn't build three plans and race them. for each table it generates paths (a seq scan, a scan of each usable index, bitmap combinations), prices each with formulas like these, and throws away any path that's beaten on every count:
hover a stage.
that's why enable_seqscan = off above didn't remove the seq scan, it just made it lose: postgres 18 counts the disabled nodes in every path and compares that count before the cost, and prints Disabled: true when it had no other choice (steering the planner). and it's why joins are priced the same way, one level at a time (join order search).
keylines
- cost units: one sequential page read = 1.0. everything else is priced against it.
- seq scan = pages × seq_page_cost + rows × (cpu_tuple_cost + cpu_operator_cost per condition).
- index scan = a descent (CPU only) + leaf pages and heap pages at random_page_cost + per-row CPU.
- heap pages are estimated with a cache model and discounted by correlation squared.
- the settings describe hardware. change them per server after measuring, not per query.