Sub topic 4
Estimated rows and width
This chapter assumes you can read the basic shape of a PostgreSQL plan, as covered earlier in this tutorial. It also assumes you know what an index is and can run SQL in psql. Here you will learn what the rows= and width= values mean, where they come from, and why a wrong rows= is the most common cause of a bad plan.
Where the numbers appear
Every plan node ends its first line with a parenthesized group of four values:
Seq Scan on orders (cost=0.00..2084.00 rows=5 width=48)
Filter: (customer_id = 42)cost=0.00..2084.00is the startup cost and the total cost. The previous chapter covered it.rows=5is the number of rows the planner expects this node to output.width=48is the expected average size of each output row, in bytes.
Both values are estimates made before the query runs. Plain EXPLAIN shows only estimates. EXPLAIN ANALYZE adds the real values next to them, and comparing the two is the subject of a later chapter.
What `rows` means
rows is the number of rows the node is expected to emit, not the number it reads. In the plan above, the sequential scan reads every row in the table (100,000 in this example). It then discards the ones that fail the filter and emits about 5. The rows=5 describes the output.
Three details are easy to miss:
- Per execution. For a node on the inner side of a nested loop,
rowsis the count for one execution of that node. Withloops=1000inEXPLAIN ANALYZE, the total is about 1000 times the displayed value. The actual rows are also reported per loop, as an average. - Never below 1. The planner rounds estimates and clamps them to at least 1. A node that shows
rows=1may really be expecting a fraction of a row. - Parent nodes inherit the error. A join, sort or aggregate above the scan uses the child's estimate as its input. A wrong number low in the tree spreads upward.
How the planner computes it
The estimate for a filtered scan is the table's row count multiplied by a selectivity. Selectivity is the fraction of rows the planner expects to pass the condition.
The diagram below shows the inputs.
The table row count comes from pg_class. You can read it directly:
SELECT reltuples::bigint AS estimated_rows, relpages
FROM pg_class
WHERE relname = 'orders';reltuples is not live. VACUUM, ANALYZE and some index builds update it. The planner also adjusts it using the table's current size in pages, so a table that has grown since the last ANALYZE is partly accounted for.
The selectivity comes from pg_stats. How it is calculated depends on the condition:
| Condition | Statistic used | Rough logic |
|---|---|---|
| `col = value` where value is common | `most_common_vals` and `most_common_freqs` | Use the recorded frequency of that value |
| `col = value` where value is not in the common list | `n_distinct` | Share the remaining fraction evenly across the remaining distinct values |
| `col < value`, `BETWEEN` | `histogram_bounds` | Count how many histogram buckets fall in the range |
| `col IS NULL` | `null_frac` | Use the stored fraction |
| `a AND b` | Both columns | Multiply the two selectivities |
Take the example above. Suppose orders has 100,000 rows and customer_id has about 20,000 distinct values. The value 42 is not common, so the selectivity is about 1/20,000. The estimate is 100,000 × (1/20,000) = 5 rows.
You can inspect these inputs yourself:
SELECT attname, n_distinct, null_frac, avg_width
FROM pg_stats
WHERE tablename = 'orders';A negative n_distinct is a ratio. For example, -1 means every value is unique, and -0.5 means the number of distinct values is half the row count and grows with the table.
What `width` means
width is the planner's estimate of the average size, in bytes, of the rows the node outputs. It is the sum of the average widths of the output columns, taken from avg_width in pg_stats. It depends on the columns you select, not on the full row size of the table.
EXPLAIN SELECT id FROM orders WHERE customer_id = 42;
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;The first plan might show width=4, because a single integer column is 4 bytes. The second shows the width of every column, such as width=48. The rows value is the same in both. Only the width changes.
Width matters for three reasons:
- Memory decisions. The planner multiplies rows by width to estimate whether a sort fits in
work_memor whether a hash table for a hash join fits in memory. If the estimate says it does not fit, the planner expects the sort to spill to disk or the hash join to split into batches, which raises its cost. - Join order. A narrower input is cheaper to hash and sort, so width can tip the choice between plans.
- A hint about what the query fetches. A large width on an inner node often means
SELECT *is dragging along wide columns such astextorjsonbthat the query never uses.
Variable-length columns make width less reliable than rows. The planner uses the average from the last ANALYZE. If a few rows hold very large values, the average can be far from the typical row.
When estimates go wrong
Row estimates fail in predictable ways. The table lists the common ones.
| Cause | What happens | Typical fix |
|---|---|---|
| Stale statistics | The table changed a lot since the last `ANALYZE` | Run `ANALYZE orders;` |
| Correlated columns | `a AND b` multiplies selectivities as if the columns were independent, so the estimate is too low | Create extended statistics |
| Skewed values with a small sample | A rare but important value is missing from `most_common_vals` | Raise the statistics target |
| Expression on a column | `WHERE lower(email) = 'x'` has no statistics, so the planner uses a default guess | Add an expression index, which also gathers statistics |
| Parameters or functions | The planner cannot see the value, so it uses a generic selectivity | Rewrite the query, or check the plan with real values |
| Join of filtered inputs | Errors in each input multiply in the join estimate | Fix the input estimates first |
The correlated-columns case is the one that surprises people most. Suppose city = 'Austin' matches 1% of rows and zip_code = '78701' matches 0.5%. The planner multiplies them and expects 0.005% of rows. In reality every row in that zip code is in Austin, so the true fraction is 0.5%, a hundred times larger. Extended statistics record that relationship:
CREATE STATISTICS orders_city_zip_stats (dependencies)
ON city, zip_code FROM orders;
ANALYZE orders;For a single column whose distribution is poorly captured, you can ask ANALYZE to sample more:
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500;
ANALYZE orders;The default statistics target is 100. ANALYZE samples about 300 times that many rows and keeps up to that many common values and histogram buckets. Raising the target makes ANALYZE slower and the statistics larger, so raise it only for columns where you have seen a bad estimate.
A quick workflow
- Run
EXPLAINon the slow query and note therowson each scan. - For each filter, ask what fraction of the table it should keep. Compare your answer with
rowsdivided by the table's row count. - If a scan looks wrong, check
pg_statsfor the column and thelast_analyzeorlast_autoanalyzetime inpg_stat_user_tables. - Run
ANALYZEon the table and explain the query again. - If the estimate is still wrong and the filter uses several columns, consider extended statistics.
Exercise
A query filters orders with WHERE status = 'shipped' AND shipped_at IS NOT NULL. The table has 1,000,000 rows. status = 'shipped' has selectivity 0.3, and shipped_at IS NOT NULL has selectivity 0.3, because they are the same rows. What rows estimate does the planner produce by default, what is the true count, and which statement would help?
Show answer
By default the planner assumes the conditions are independent and multiplies them: 1,000,000 × 0.3 × 0.3 = 90,000 rows. Because the two columns are perfectly correlated, the true count is about 300,000. The estimate is too low by a factor of more than three. Running CREATE STATISTICS orders_status_shipped_stats (dependencies) ON status, shipped_at FROM orders; followed by ANALYZE orders; lets the planner account for the dependency.
Exercise
You run EXPLAIN SELECT * FROM orders WHERE customer_id = 42; and then EXPLAIN SELECT id FROM orders WHERE customer_id = 42;. Which of rows and width changes between the two plans, and why?
Show answer
Only width changes. The rows estimate depends on the filter and the statistics for customer_id, which are the same in both queries. The width is the sum of the average widths of the output columns, so selecting only id gives a much smaller width than selecting every column.