Sub topic 12
A workflow for diagnosing bad estimates
This chapter assumes you can read basic EXPLAIN output and know what ANALYZE, pg_stats, and autovacuum do. Earlier chapters covered each piece separately. Here you will use them together, in a fixed order, so that a slow query leads you to a specific fix and not to guesswork.
Why a workflow helps
A bad plan is usually a symptom. The planner picked a nested loop over a hash join, or a sequential scan over an index scan, because it believed a step would return a different number of rows than it did. Fixing the plan directly with hints or settings treats the symptom. Fixing the estimate treats the cause, and it helps every other query that touches the same data.
The causes fall into a short list, and cheap checks come before expensive fixes. The order is:
- Find the node where the estimate first goes wrong.
- Check whether the statistics are fresh.
- Check whether the statistics capture the column's distribution.
- Check whether the filter depends on more than one column or on an expression.
- Fix the cause, then verify.
Step 1: Find the first wrong node
Use the orders table from earlier chapters. Run:
EXPLAIN (ANALYZE)
SELECT * FROM orders WHERE status = 'pending';Each node shows two row counts: rows= inside the cost parentheses is the estimate, and rows= inside the actual parentheses is what happened. With fresh statistics the two should be close, since about 5% of 100,000 rows are pending.
Three reading rules prevent most mistakes:
- Start at the bottom. Errors propagate upward. A join node that is off by 1000x is often only inheriting a bad scan estimate below it. Fix the lowest node whose gap is large.
- Multiply actual rows by loops. Under a nested loop,
actual rowsis an average per execution. The real total isrows × loops. Compare the estimate with the per-loop figure, because the estimate is also per execution. - Look at the size of the gap, not its existence. An estimate of 4,800 against 5,050 actual is fine. A gap of 10x or more is worth investigating, and it matters most when it flips the plan choice, such as when it crosses the point where an index scan stops paying off.
Also note Rows Removed by Filter. A scan that reads 100,000 rows to return 5,000 tells you how selective the filter really was.
Step 2: Check freshness
Stale statistics are the cheapest cause to rule out:
SELECT relname, last_analyze, last_autoanalyze, n_mod_since_analyze
FROM pg_stat_user_tables
WHERE relname = 'orders';A large n_mod_since_analyze relative to the table size, or timestamps from long ago, means the planner is working from an old picture. This happens after bulk loads, big deletes, or a new value appearing in a column (for example a new status that did not exist at the last analyze). The planner has no entry for it and falls back to a generic guess.
Run ANALYZE orders; and repeat the EXPLAIN ANALYZE. If the estimate now matches, the problem was freshness, and you move on to Step 5 to make it stop recurring. If it does not change, the statistics are current but inadequate.
Step 3: Check the distribution
If fresh statistics still give a bad estimate for a single-column filter, look at what was stored:
SELECT attname, null_frac, n_distinct, most_common_vals, most_common_freqs, histogram_bounds, correlation
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname IN ('status', 'customer_id');Ask these questions of the row for the filtered column:
- Is the value in
most_common_vals? If so, the estimate is its frequency times the row count, and it should be accurate. If not, the planner spreads the leftover fraction over the remaining distinct values, or uses the histogram for range filters. - Is
n_distinctplausible? Sampledn_distinctcan be badly wrong on large tables, especially for columns with many distinct values. A negative value means a fraction of the row count (-1means every row is unique). - Is the distribution too detailed for the default? With the default target of 100,
ANALYZEkeeps up to 100 common values and 100 histogram buckets. A column with a long tail of moderately common values, such as acustomer_idwith a few thousand active customers, loses information.
When the answer is the last one, raise the target for that column only:
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500;
ANALYZE orders;SET STATISTICS only records the new target. The change has no effect until the next ANALYZE. A higher target means a larger sample (about 300 times the target in rows), more space in pg_statistic, and slightly more planning time. Raise it where evidence shows it helps, not across the board. Going from 100 to 500 is a reasonable first step. Values near the maximum of 10,000 are rarely justified.
Step 4: Check for correlated columns and expressions
If the filter touches several columns and each column's statistics look fine, the planner's independence assumption is the likely culprit. It multiplies the selectivities of each condition, which is wrong when the columns are related. Build a small reproduction:
CREATE TABLE addresses (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
city text NOT NULL,
zip text NOT NULL
);
INSERT INTO addresses (city, zip)
SELECT 'city_' || ((g % 1000) / 10),
'zip_' || (g % 1000)
FROM generate_series(1, 100000) AS g;
ANALYZE addresses;
EXPLAIN (ANALYZE)
SELECT * FROM addresses WHERE city = 'city_5' AND zip = 'zip_55';Each zip belongs to exactly one city, so the true count is 100 rows. The planner multiplies 1/100 for the city by 1/1000 for the zip and estimates about 1 row. That is a 100x underestimate. This tends to push the planner toward nested loops, which are slow once the real row count shows up.
Tell the planner about the dependency:
CREATE STATISTICS addresses_city_zip (dependencies, ndistinct)
ON city, zip FROM addresses;
ANALYZE addresses;Re-run the EXPLAIN ANALYZE. The estimate should move to roughly 100. You can inspect what was collected:
SELECT statistics_name, dependencies, n_distinct
FROM pg_stats_ext
WHERE statistics_name = 'addresses_city_zip';Choose the statistics kind to match the problem:
| Symptom | Kind | What it fixes |
|---|---|---|
| Equality filters on columns where one determines the other | `dependencies` | Combined selectivity of `WHERE` clauses |
| `GROUP BY` or `DISTINCT` on several columns gives a wrong group count | `ndistinct` | Estimated number of distinct combinations |
| Combinations of values that never co-occur, or co-occur often | `mcv` | Joint frequency of specific value pairs |
On PostgreSQL 14 and later, CREATE STATISTICS also accepts expressions, which helps filters like WHERE lower(email) = ... where the planner has no statistics for the expression and falls back to a default guess. An expression index also creates statistics for its expression.
If none of this applies, look beyond single-table filters. Join estimates depend on n_distinct for both join columns. Filters using functions, casts, or LIKE patterns with a leading wildcard get default selectivities. Prepared statements may use a generic plan that ignores the actual parameter value.
Step 5: Make the fix stick
If Step 2 showed stale statistics, find out why autoanalyze did not keep up. Autovacuum re-analyzes a table when the number of changed rows exceeds autovacuum_analyze_threshold + autovacuum_analyze_scale_factor × reltuples. With the defaults (50 and 0.1), a table of 100 million rows must change by about 10 million rows before it is re-analyzed. For a large table with a skewed or fast-moving column, that is too late.
ALTER TABLE orders SET (autovacuum_analyze_scale_factor = 0.02);This triggers a re-analyze after about 2% of rows change. Lowering the setting costs more frequent, but sampled and therefore bounded, analyze work. If a batch job loads data and immediately queries it, do not wait for autovacuum at all. Run ANALYZE as the last step of the job.
Step 6: Verify
Re-run the original EXPLAIN (ANALYZE) and check three things: the estimate at the formerly wrong node, the plan shape, and the execution time. A better estimate that does not change the plan or improve timing was not the bottleneck, so go back to Step 1 and look at the next node. Record what you changed. Per-column targets and extended statistics persist in the catalog, so they are part of the schema's behavior and worth documenting.
Common errors
- Raising
default_statistics_targetglobally when only one column needs it. This inflates analyze time and planning time everywhere. - Fixing the join node when the scan below it is the real problem.
- Forgetting
ANALYZEafterSET STATISTICSorCREATE STATISTICS. - Reading
actual rowsfor a looped node without multiplying byloops. - Diagnosing a single run on a cold cache. Estimates do not depend on caching, but timing does, so run the query twice before judging speed.
Exercise
An EXPLAIN ANALYZE shows a Hash Join estimated at 10 rows but actually returning 40,000. Its child Seq Scan on table a is estimated at 12 rows and returns 48,000. Which node do you investigate first, and what is your first check?
Show answer
Investigate the Seq Scan on a, the lowest node with a large gap. The join's error is likely inherited from it. First check freshness with pgstatusertables (lastanalyze, lastautoanalyze, nmodsinceanalyze), then run ANALYZE on a and compare the estimate again.
Exercise
A query filters on country = 'DE' AND language = 'de'. Both columns have accurate statistics, but the planner estimates 20 rows and the query returns 20,000. What is the likely cause, and which statement fixes it? What must you do afterwards?
Show answer
The planner assumes the two columns are independent and multiplies their selectivities, but language depends on country. Create extended statistics, for example CREATE STATISTICS countrylanguage (dependencies) ON country, language FROM yourtable; then run ANALYZE on the table, because the new statistics are only populated by the next ANALYZE.