Sub topic 3
What the cost numbers mean
This chapter assumes you can run EXPLAIN in psql and know that a plan is a tree of nodes. It also assumes you know roughly what an index does. The chapter explains the two numbers after cost= on every plan line, how PostgreSQL computes them, and what they can and can't tell you.
The two numbers in cost=
Every node in a PostgreSQL plan carries a cost range:
Seq Scan on orders (cost=0.00..22500.00 rows=50000 width=64)
Filter: (status = 'open'::text)The two numbers are separated by two dots:
- Startup cost (
0.00) is the estimated work done before the node can return its first row. - Total cost (
22500.00) is the estimated work to return all of its rows.
A sequential scan can return rows immediately, so its startup cost is near zero. A Sort can't return anything until it has read and sorted all its input, so its startup cost is almost as large as its total cost.
The rows and width values on the same line are covered in the next chapter. Cost depends on the estimated rows a node must process, but the cost range is a separate output.
Cost is not time
Cost has no unit. It is not milliseconds, and it is not a count of disk reads. It is a relative figure measured against one reference: reading one 8 kB page sequentially from disk costs 1.0.
Because of that, you can only compare costs under these conditions:
- The costs come from the same server, with the same settings.
- The costs belong to the same query, or to alternative plans for it.
- You are comparing plans from the same version of the statistics.
A cost of 22500 on one server says nothing about how long the query runs on another. The planner uses the numbers only to rank candidate plans and pick the cheapest. To learn real time, you need EXPLAIN ANALYZE, which a later chapter covers.
Where the numbers come from
The planner adds up five per-operation prices. They are configuration parameters, and you can read them with SHOW:
| Parameter | Default | What it prices |
|---|---|---|
| `seq_page_cost` | 1.0 | Reading one page as part of a sequential scan |
| `random_page_cost` | 4.0 | Reading one page at a non-sequential position, as an index does |
| `cpu_tuple_cost` | 0.01 | Processing one row |
| `cpu_index_tuple_cost` | 0.005 | Processing one index entry |
| `cpu_operator_cost` | 0.0025 | Running one operator or function, such as `=` in a filter |
SELECT name, setting
FROM pg_settings
WHERE name IN (
'seq_page_cost', 'random_page_cost', 'cpu_tuple_cost',
'cpu_index_tuple_cost', 'cpu_operator_cost'
);The planner multiplies each price by an estimated quantity. The quantities come from the table's size in pages and the estimated row counts. PostgreSQL keeps the page and row counts in pg_class:
SELECT relpages, reltuples
FROM pg_class
WHERE relname = 'orders';A worked example: pricing a sequential scan
Suppose orders occupies 10,000 pages and holds 1,000,000 rows. You run this:
EXPLAIN
SELECT *
FROM orders
WHERE status = 'open';The planner prices a sequential scan with this formula:
total = pages * seq_page_cost
+ rows * cpu_tuple_cost
+ rows * cpu_operator_cost * (number of filter conditions)With the example numbers:
- Disk: 10,000 pages × 1.0 = 10,000.
- Row handling: 1,000,000 rows × 0.01 = 10,000.
- Filter: 1,000,000 rows × 0.0025 × 1 condition = 2,500.
The sum is 22,500, which matches cost=0.00..22500.00 in the plan above. Startup cost is 0.00 because the scan needs no preparation.
Two details are worth noting. The filter is charged for every row the scan reads, not only for the rows that pass. The estimated output of 50,000 rows does not change this cost. Also, your own plans will rarely show round numbers like these, because real tables have fractional row counts and several filter conditions. The arithmetic is the same.
Costs accumulate up the tree
A parent node's cost includes the cost of its children. When you read a plan, the top node's total cost is the estimate for the whole query.
In this sketch:
- The
Hashnode's startup cost is its input's total cost, because it must read all ofcustomersto build the table in memory. - The
Hash Joincan't start producing rows until the hash is built, so its startup cost includes that work. - The root's total cost is the sum of its own work plus its children's.
This is why the fastest way to find where cost enters a plan is to look for a large jump between a child's total and its parent's total. The Hash Join in the diagram adds 8,500 over its first child's cost. That tells you the join itself, not a scan, produced that part of the estimate.
Startup versus total: why both matter
Two plans can have the same total cost but behave differently. The difference shows when a query has a LIMIT.
The planner assumes the parent will stop pulling rows early. It then estimates a fraction of the child's work:
partial cost = startup + (total - startup) * (rows needed / rows produced)Take the sequential scan from earlier. It has a total cost of 22,500 and an estimated 50,000 output rows. Add LIMIT 10:
EXPLAIN
SELECT *
FROM orders
WHERE status = 'open'
LIMIT 10;The plan looks like this:
Limit (cost=0.00..4.50 rows=10 width=64)
-> Seq Scan on orders (cost=0.00..22500.00 rows=50000 width=64)
Filter: (status = 'open'::text)The Limit cost is 0 + 22,500 × 10 / 50,000 = 4.50. The scan node still shows its full cost range, because that range describes the node running to completion. The limit simply expects not to need all of it.
A node with a high startup cost, such as a Sort, gets little benefit from a limit. The sort must finish before the first row is available, so only the part after startup is scaled down.
The planner can be wrong about this. It assumes matching rows are spread evenly through the table. If the first matching rows are actually at the end, the scan reads far more than the estimate.
Why the planner picks an index
Compare the sequential scan's cost with an index scan's cost. An index scan is charged random_page_cost for the table pages it fetches, and 4.0 is four times the sequential price. For a filter that matches a large share of the table, those random reads add up to more than reading the whole table in order. The planner then chooses the sequential scan, even though an index exists.
CREATE INDEX orders_status_idx ON orders (status);
ANALYZE orders;
EXPLAIN
SELECT *
FROM orders
WHERE status = 'open';If status = 'open' matches half the rows, expect the plan to stay a Seq Scan. If it matches a handful of rows, expect an index-based scan. The cost model makes this decision, so you can predict it from the match fraction.
What cost does not include
The cost model leaves out several things, which explains many surprises:
- Cache state. The planner does not know which pages are already in memory. It prices reads as if they came from disk, except that the
effective_cache_sizesetting nudges index estimates. - Network and client time. Sending rows to the client costs nothing in the plan.
- Lock waits and contention. A blocked query can be slow with a low cost.
- Estimation errors. Cost is computed from estimated rows. If the row estimate is wrong, every cost above that node is wrong too.
Common mistakes
- Reading cost as milliseconds. Convert nothing. Compare only relative sizes.
- Comparing costs between different queries. A cost of 500 for one query does not mean it is cheaper than a query costing 900 on different data.
- Ignoring startup cost. For interactive queries that return the first rows quickly, startup cost matters more than total.
- Tuning cost parameters first. Change
random_page_costonly when you know your storage differs from the defaults. Fix statistics and indexes before touching the cost settings.
Exercise
A table has 5,000 pages and 400,000 rows. You run a query that filters it with one condition, and the planner chooses a sequential scan. Using the default cost parameters, what total cost do you expect to see on the Seq Scan line? If the same scan sits under a Limit node that needs 20 rows out of an estimated 8,000 output rows, what total cost does the Limit node show?
Show answer
Scan: 5,000 × 1.0 = 5,000 for pages, 400,000 × 0.01 = 4,000 for row handling, and 400,000 × 0.0025 × 1 = 1,000 for the filter. The total is 10,000, so the line shows cost=0.00..10000.00. For the Limit node, startup is 0 and the partial cost is 0 + 10,000 × 20 / 8,000 = 25.00, so it shows cost=0.00..25.00.