Sub topic 12
A Workflow for Diagnosing Bad Estimates
Assume you know basic SELECT, WHERE, JOIN, and CREATE TABLE statements. You should also be able to run psql and read a simple EXPLAIN plan.
PostgreSQL uses a cost-based planner. The planner estimates how many rows each plan step will produce, then compares possible plans. These estimates influence choices such as sequential scan versus index scan, and nested loop versus hash join. A bad estimate can therefore produce a slow plan even when suitable indexes exist.
A useful diagnosis follows this path:
Start with estimated and actual rows
Use EXPLAIN (ANALYZE, BUFFERS) for a representative query:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE status = 'pending';EXPLAIN shows the plan chosen by PostgreSQL. ANALYZE executes the query and adds measurements from the execution. For every plan node, compare rows= with actual rows=.
| Estimate | Actual rows | Likely meaning |
|---|---|---|
| 100 | 95 | The estimate is probably useful |
| 100 | 10,000 | The planner underestimated selectivity |
| 10,000 | 100 | The planner overestimated selectivity |
A large difference at an early node can multiply through later joins. Also check loops. If a node reports actual rows=20 loops=500, it produced 20 rows per loop, not 20 rows in total. Compare the estimate with the per-loop actual value.
Check whether statistics are current
First inspect when PostgreSQL last analyzed the table:
SELECT relname, last_analyze, last_autoanalyze, n_mod_since_analyze
FROM pg_stat_user_tables
WHERE relname = 'orders';If the table has changed substantially, refresh its statistics:
ANALYZE orders;VACUUM ANALYZE orders; also reclaims or marks reusable storage and then collects statistics. Use it when you need both maintenance operations. ANALYZE alone is usually the smaller and faster diagnostic action.
Next inspect the values that the planner knows about:
SELECT attname, null_frac, n_distinct,
most_common_vals, most_common_freqs,
histogram_bounds, correlation
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders';most_common_vals and most_common_freqs help with common values such as a heavily used status. histogram_bounds represents the distribution of other values. If a recently introduced value is missing, the statistics may be stale or the sample may not represent the distribution well.
Improve statistics when ANALYZE is not enough
A column with many distinct or highly uneven values may need a larger statistics target:
ALTER TABLE orders
ALTER COLUMN customer_id SET STATISTICS 500;
ANALYZE orders;The higher target makes PostgreSQL keep a larger sample and more detailed per-column statistics. It also increases analysis time and catalog storage, so apply it only to columns that need it.
Single-column statistics cannot fully describe relationships between columns. If city and zip are correlated, create extended statistics:
CREATE STATISTICS addresses_city_zip
(dependencies, ndistinct)
ON city, zip
FROM addresses;
ANALYZE addresses;The new information becomes useful after ANALYZE. Extended statistics help the planner estimate combined predicates, but they do not replace indexes or guarantee a particular plan.
Tune automatic analysis
Autovacuum normally analyzes tables after enough rows change. For a table where a small percentage of changes greatly alters its distribution, lower its analyze scale factor:
ALTER TABLE orders SET (
autovacuum_analyze_scale_factor = 0.02
);The threshold is approximately a fixed threshold plus the scale factor multiplied by the table's row count. Monitor last_autoanalyze and n_mod_since_analyze after changing the setting.
Exercise
What should you check first when EXPLAIN ANALYZE shows a poor plan and the estimated rows differ greatly from the actual rows?
Show answer
Check when the table was last analyzed and run ANALYZE if its data has changed. Then inspect pg_stats before raising a statistics target or adding extended statistics.