When the planner expects 100 rows and gets a million
The planner chooses a join order, a join algorithm and memory sizes from estimated row counts. When an estimate is wrong, every decision above it inherits the error. A scan estimated at 100 rows may lead to a nested loop that is excellent for 100 rows and catastrophic for a million; the same query with a correct estimate would have chosen a hash join.
PostgreSQL estimates from statistics in pg_statistic, collected by ANALYZE or autovacuum. For each column it stores a sample, a null fraction, a distinct-count estimate, a most-common-values list and a histogram of the rest. For a simple equality on a common value, the estimate is accurate. For a value not in the list, it assumes an average frequency, which can be far from reality on a skewed column.
| Cause | Symptom | Fix |
|---|---|---|
| Stale statistics | Table grew or changed since last ANALYZE | Run ANALYZE, tune autovacuum |
| Correlated columns | Each predicate estimate is fine, the combination is not | CREATE STATISTICS with dependencies |
| Function on a column | Estimate is a fixed default percentage | Index the expression or store a normalised column |
| Skewed distribution | Common value treated as average | Increase statistics target, check MCV list |
| Out-of-range value | Estimate collapses to a default | Refresh stats; check partition bounds |
| Join across unrelated tables | Estimate assumes independence | Extended stats or a rewrite |
Reading the ratio
In EXPLAIN ANALYZE, each node has estimated rows and actual rows. The analyzer computes the ratio in both directions and flags values above ten when the row count is large enough to matter. A ratio of 0.01 and a ratio of 100 are the same kind of error: the planner thought the set was a hundred times smaller or larger than it was.
Look at where the error first appears. If a scan's estimate is right but the join above it is wrong, the join condition or the combination of filters is the problem. If the scan itself is wrong, the column statistics are the place to start. Fixing the lowest wrong node often corrects the whole plan, because the estimates above are derived from it.
Statistics in practice
The default statistics target is 100, which samples a few thousand rows. For a large table with a skewed column, raising the target on that column gives a better MCV list and histogram: ALTER TABLE orders ALTER COLUMN status SET STATISTICS 500;, then ANALYZE. The cost is a larger pg_statistic and slightly slower planning, which is usually worth it for a column used in every query.
Correlated columns need extended statistics. If a table stores city and district, the planner multiplies their selectivities as if independent, which underestimates a combination that always occurs together. CREATE STATISTICS orders_city_district (dependencies, ndistinct) ON city, district FROM orders; followed by ANALYZE gives the planner the relationship. Multivariate MCV lists help when a few combinations dominate.
Predicates the planner cannot estimate
A function on a column hides the distribution: WHERE lower(email) = 'a@example.com' cannot use the statistics for email. The planner falls back to a default selectivity, often 0.5 percent, whatever the real match rate. The fixes are to index the expression so the plan can use it, or to store a normalised column and filter on that. The same applies to casts that change the type, arithmetic on a column, and pattern matching with a leading wildcard.
OR conditions across columns are another blind spot. The planner estimates each side and combines them with a formula that assumes some independence; the result can be wildly off when the conditions overlap. Rewriting as a UNION of two indexed queries sometimes gives both a better estimate and a better plan, at the cost of two scans.
A diagnostic order
- Find the node with the largest ratio and note whether it is a scan or a join.
- Check when the table was last analyzed and how much it changed since.
- Look at the column's statistics target and most-common-values list.
- Check whether the predicate applies a function, cast or pattern to the column.
- Check whether two filtered columns are correlated in the data.
- Refresh or extend statistics, re-run EXPLAIN ANALYZE, and compare the new ratio.
Do not chase estimate accuracy for its own sake. The goal is a plan that runs well with the data you have. Sometimes a deliberately imperfect estimate still produces the right plan, and sometimes a perfect estimate changes nothing because the time is in a sort or an I/O bottleneck. Use the ratio to find suspicious nodes, then confirm with measured time.
An estimate error is not the bug; it is the clue. The bug is usually a statistic the planner does not have or a predicate it cannot read.
Sources
- PostgreSQL documentation — Statistics used by the planner
- PostgreSQL documentation — CREATE STATISTICS
- PostgreSQL documentation — ANALYZE
Questions
How far off is too far?
A factor of two is normal and usually harmless. A factor above ten on a node with thousands of rows is worth investigating, because join order and memory decisions above it are based on the wrong size. A factor of a thousand on a large table almost always explains a bad plan.
Does ANALYZE fix every estimate?
No. It refreshes the sample that statistics are built from, which fixes stale data. It does not help when the predicate is a function the planner cannot estimate, when two columns are correlated and no extended statistics exist, or when the value is outside the histogram and falls back to a default selectivity.
What are extended statistics?
Objects created with CREATE STATISTICS that describe relationships between columns: functional dependencies, distinct counts for column groups, and multivariate MCV lists. They let the planner estimate a combination like city = 'Seoul' AND district = 'Gangnam' far better than multiplying two independent probabilities.
The analyzer prints the actual-to-estimate ratio on every node and flags ratios above ten.
Open the analyzerWritten against the PostgreSQL and MySQL documentation and the standard cost model; every plan in the examples can be pasted into the analyzer linked above.
Back to the guides