How does PostgreSQL's query planner use table statistics?

The planner never counts rows before running a query. It estimates them from statistics that ANALYZE sampled earlier, stored in pg_statistic and read through the pg_stats view. Those estimates decide index versus sequential scan, nested loop versus hash join. When an estimate is wrong, the plan is wrong — and almost every bad plan starts there.

Key facts

| Fact | Value | |---|---| | Where statistics live | pg_statistic, readable only through the pg_stats view; pg_statistic itself is not readable by a monitoring role | | What ANALYZE collects | null fraction, n_distinct, most-common values and frequencies, histogram bounds, physical correlation (planner statistics) | | default_statistics_target | 100 — the number of MCV slots and histogram buckets per column (docs) | | ANALYZE sample size | roughly 300 × statistics target rows, not the whole table (ANALYZE) | | Autovacuum ANALYZE trigger | autovacuum_analyze_threshold 50 + autovacuum_analyze_scale_factor 0.1 × reltuples (docs) | | Multi-column fix | CREATE STATISTICS ... (ndistinct, dependencies, mcv) — ndistinct/dependencies in PG10+, MCV in PG12+ (docs) | | Across 50 monitored instances | 28.0% fail the dead-tuples check and 8.0% the stale-autovacuum check; 52.0% show at least one plan regression |

Why this happens

PostgreSQL's planner is a cost model. For every candidate plan it asks one question first: how many rows will this node emit? Everything downstream — whether an index is worth the random I/O, whether a nested loop beats a hash join, whether a sort fits in work_mem — follows from that number. The planner statistics chapter is explicit that these are estimates derived from a sample, never counts.

ANALYZE stores five things per column, and each feeds a different part of a selectivity calculation (row estimation examples):

default_statistics_target (100) controls how many MCV slots and histogram buckets exist, and therefore how much detail the planner has. Raising it per column is cheap and targeted:

ALTER TABLE orders ALTER COLUMN status SET STATISTICS 500;
ANALYZE orders;

The sample is not the table

ANALYZE reads a random sample of roughly 300 × statistics_target rows — 30,000 rows at the default — regardless of whether the table holds a million rows or a billion. null_frac and the histogram survive sampling well. n_distinct does not. Estimating the number of distinct values in a population from a sample is a known-hard statistical problem, and PostgreSQL's estimator systematically undershoots on large tables with many distinct values.

An n_distinct that is too low makes every equality estimate too high; too high makes them too low. When you know the truth, override it. The value is remembered and survives ANALYZE:

-- absolute count
ALTER TABLE events ALTER COLUMN tenant_id SET (n_distinct = 5000);
-- or a negative number: a fraction of the table (here, distinct in 1 row of every 100)
ALTER TABLE events ALTER COLUMN session_id SET (n_distinct = -0.01);
ANALYZE events;

Correlated columns: the biggest single cause

Per-column statistics describe columns in isolation, and the planner combines them by multiplying. For WHERE city = 'Bristol' AND postcode = 'BS1 4ST' it computes sel(city) × sel(postcode) — an assumption of statistical independence that the data flatly contradicts. Postcode determines city. The true selectivity is roughly that of postcode alone; the planner's product can be hundreds or thousands of times smaller.

The planner then estimates one row where thousands exist, chooses a nested loop, and the query that used to take 40 ms takes four minutes. This is the failure mode behind most "it was fine yesterday" incidents, and it is a recurring theme in Postgres query anti-patterns.

Extended statistics are the supported fix (multivariate statistics examples):

CREATE STATISTICS addresses_city_postcode (ndistinct, dependencies, mcv)
  ON city, postcode FROM addresses;
ANALYZE addresses;

Stale statistics after a bulk load

Autovacuum only queues an ANALYZE when changed tuples exceed autovacuum_analyze_threshold + autovacuum_analyze_scale_factor × reltuples — 50 rows plus 10% of the table by default. On a 200-million-row table that is 20 million changes. Load 5 million fresh rows overnight and the planner keeps planning as if they do not exist, sometimes for days. The same arithmetic is why large tables need per-table overrides; see autovacuum tuning.

There is no waiting on autovacuum in a load job. Run ANALYZE yourself as the last step.

How to detect it

Start in the plan. EXPLAIN ANALYZE prints the planner's estimate and the truth side by side (EXPLAIN):

EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM addresses WHERE city = 'Bristol' AND postcode = 'BS1 4ST';
Index Scan using addresses_city_idx on addresses
  (cost=0.43..8.46 rows=1 width=84) (actual time=0.031..19.402 rows=3184 loops=1)

rows=1 is the estimate, actual rows=3184 is reality: a 3,184× underestimate on a single node. Read the ratio, not the absolute numbers. Then read it upward — a 100× error at a leaf becomes a 100× error in every join above it, because each join multiplies its inputs' estimates. This is why bad join orders are usually a statistics problem rather than a join problem; the same point in reverse is covered in Postgres join optimization.

Next, look at what the planner actually knows about the column:

SELECT attname, null_frac, n_distinct, correlation,
       array_length(most_common_vals, 1) AS mcv_count,
       array_length(histogram_bounds, 1) AS histogram_buckets
FROM pg_stats
WHERE schemaname = 'public' AND tablename = 'addresses';

pg_stats is the route. The underlying pg_statistic catalog is not readable by an ordinary monitoring role — pg_monitor membership does not grant it — so any tooling that reads the catalog directly will come back empty while pg_stats works fine.

And find tables ANALYZE has never touched, or has not touched recently:

SELECT schemaname, relname, n_live_tup, n_mod_since_analyze,
       last_analyze, last_autoanalyze
FROM pg_stat_user_tables
WHERE last_analyze IS NULL AND last_autoanalyze IS NULL
   OR n_mod_since_analyze > greatest(1000, n_live_tup * 0.1)
ORDER BY n_mod_since_analyze DESC;

A row with both last_analyze and last_autoanalyze NULL has never been analysed at all, and every plan touching it is built on a hardcoded default guess.

How MyDBA shows this

The Regressed lens on the Queries page, listing queries whose latency rose against their own baseline without a code change.

Statistics drift is hard to see because nothing deploys when it happens — the query text is identical and the plan is not. MyDBA's Queries page carries a Regressed lens (alongside Top and Slow now) that compares each query's recent 15-minute mean against its own 24-hour baseline, with selectable severity presets of ≥25%, ≥75% and ≥200% over baseline, a 5 ms floor so that 1 ms→2 ms noise does not surface, and a call-count guard. Collected plans are kept with their estimated and actual row counts, so a query flagged as regressed can be opened against the plan that replaced the old one.

A collected plan where the planner's estimated rows and the actual rows disagree by two orders of magnitude, the fingerprint of stale statistics.

The health checks cover the upstream cause. Across 50 monitored instances, 28.0% fail the dead-tuples check and 8.0% fail the stale-autovacuum check, while 52.0% show at least one plan regression — a reminder that regressions are common and that stale maintenance is a plausible first suspect rather than a rare one. If you want the same picture of your own instances, start with the free PostgreSQL health check.

How to fix it

1. Get the plan. EXPLAIN (ANALYZE, BUFFERS) on the real query with real parameters. 2. Find the deepest node where the estimate first goes wrong. Work bottom-up and stop at the first large estimate-versus-actual ratio. Nodes above it are wrong because it is wrong; fixing them is wasted effort. 3. ANALYZE the table that node scans. Often that alone is the fix, especially after a load or a migration. 4. Check pg_stats for that column. If n_distinct disagrees with SELECT count(DISTINCT col), override it with SET (n_distinct = ...). 5. If the predicate names two or more columns, add extended statistics with CREATE STATISTICS ... (ndistinct, dependencies, mcv) and re-analyse. Check it took effect in pg_stats_ext. 6. If the column is skewed and the bad literal is a rare value, raise the target. SET STATISTICS 1000 gives 1,000 MCV slots and a 300,000-row sample for that column, then ANALYZE. 7. Re-run the plan and compare the same node. If the ratio did not move, the statistics were not the problem — go look at the query shape instead.

How to prevent it

Make ANALYZE the last statement of every bulk load and every data migration; it costs seconds and removes the most common cause of a next-morning incident. Lower autovacuum_analyze_scale_factor per table on your largest tables, where 10% of reltuples is an unreasonable amount of drift to tolerate:

ALTER TABLE events SET (autovacuum_analyze_scale_factor = 0.01,
                        autovacuum_analyze_threshold = 5000);

Create extended statistics at schema-design time on the column pairs you already know are correlated — city/postcode, country/currency, product/category, tenant/region. They cost a little ANALYZE time and nothing at plan time.

Finally, monitor pg_stat_user_tables.last_autoanalyze and alert on tables whose statistics are older than the data they describe. The failure is silent: the query keeps returning correct results, just slowly, and nobody notices until a customer does.

FAQ

Does ANALYZE lock the table?

No. ANALYZE takes only a SHARE UPDATE EXCLUSIVE lock, so reads and writes continue normally (ANALYZE). It conflicts with VACUUM and with other ANALYZE runs on the same table, and with schema changes, but not with ordinary traffic. Running it after a bulk load is safe on a live system.

Why did raising default_statistics_target not help?

Because the error was not a shortage of buckets. A per-column target only refines single-column selectivity. If the underestimate comes from multiplying two correlated predicates, no target is high enough — the planner is multiplying independent probabilities that are not independent. That needs CREATE STATISTICS. Raising the target globally also lengthens every ANALYZE and every plan, so prefer per-column changes.

How do I tell a statistics problem from a query problem?

Compare rows= with actual rows= at each node. If the estimates are close and the node is still slow, the statistics are fine and the cost is real — the query, the indexes or the data volume needs work. If the estimates are off by an order of magnitude or more, the planner chose that plan on bad information, and no rewriting will reliably help until the estimate is corrected.

Do extended statistics work on expressions?

Yes. Since PostgreSQL 14, CREATE STATISTICS accepts expressions as well as bare columns, which covers predicates like WHERE lower(email) = ... (docs). Before that, the usual workaround was an expression index, which also causes ANALYZE to collect statistics on the indexed expression.

Part of the Reading PostgreSQL EXPLAIN and EXPLAIN ANALYZE Output guide. Last verified against PostgreSQL 18, 2026-09-17.