Statistics and the Planner

Topics Covered

What ANALYZE Collects

Sampling, not scanning

Per column statistics

n_distinct and its sign

Most common values

Histograms

Correlation

Table level statistics

Statistics on inheritance and partitions

Who runs ANALYZE

Inspecting statistics

How the statistics target scales the sample

Statistics and privileges

Statistics after upgrades and restores

Statistics on temporary tables

When statistics are enough

The PostgreSQL planner chooses among many possible plans by estimating how many rows each step will produce and what each will cost. Those estimates rest almost entirely on statistics that ANALYZE gathers by sampling tables. When statistics are accurate and current, the planner is usually right; when they are stale, too coarse or blind to relationships between columns, it makes the bad choices seen in the previous lesson. This section explains what ANALYZE collects, how it samples and where the results live.

Sampling, not scanning

ANALYZE does not read whole tables. It reads a random sample of 300 times the statistics target rows, so with the default target of 100 it samples 30000 rows, chosen from random pages across the table. This keeps ANALYZE fast even on very large tables, at the cost of statistics that are estimates and can vary slightly between runs. Because the sample size does not grow with the table, a billion row table gets the same 30000 row sample as a million row table, which is usually enough for common values but can miss rare ones.

ANALYZE reads a fixed size random sample, 300 times the statistics target, and summarizes each column from it.

Per column statistics

For each column, ANALYZE computes and stores in pg_statistic, viewable through pg_stats, the fraction of nulls, null_frac, the average width in bytes, avg_width, and the number of distinct values, n_distinct. It also keeps a list of the most common values with their frequencies, most_common_vals and most_common_freqs, and a histogram_bounds array dividing the remaining values into buckets of equal population. Finally it records correlation, between minus one and one, measuring how closely the physical order of rows follows the sorted order of the column values.

n_distinct and its sign

n_distinct is stored as a positive number when ANALYZE believes the number of distinct values is fixed, such as 50 for a status column, and as a negative fraction of the row count when it believes distinct values grow with the table, such as minus one for a unique column, meaning every row is distinct. Estimating distinct values from a sample is statistically hard, and n_distinct is often underestimated for columns with many rare values. ALTER TABLE ALTER COLUMN SET (n_distinct) overrides the estimate when the true value is known.

Most common values

The most common values list stores up to statistics target entries for values that appear notably more often than average in the sample, with their frequencies. An equality condition on one of these values gets an exact frequency estimate. For skewed columns, such as a tenant_id where a few tenants own most rows, the list is what lets the planner know that tenant 1 has 40 percent of the rows while tenant 900 has a hundredth of a percent. Values not in the list are assumed to share the remaining frequency equally.

Histograms

The histogram divides values that are not in the most common list into buckets containing roughly equal numbers of rows, storing only the boundaries. For a range condition, the planner finds where the bounds fall, counts whole buckets inside the range and interpolates within partial buckets. With 100 buckets, each represents about one percent of the non common rows, so estimates for ranges are good to about a percent, and finer for higher targets. Columns with few distinct values have no histogram, since most common values cover them.

Each histogram bucket holds an equal share of rows. A range covering two and a half buckets is estimated at two and a half shares.

Correlation

The correlation statistic is the correlation between the physical order of rows and the sorted order of the column. A timestamp in an append only table has correlation near 1, so an index range scan reads heap pages almost sequentially, and the planner costs it cheaply. A random UUID column has correlation near 0, so each index entry points to a random page, and the planner charges random_page_cost for most fetches. Correlation is why the same index scan can be estimated cheap on one column and expensive on another for the same row count.

Table level statistics

Besides column statistics, pg_class stores reltuples, the estimated number of rows, and relpages, the number of pages, updated by vacuum and ANALYZE. At planning time, the planner reads the current number of pages from the file size and scales reltuples by the ratio, so a table that doubled in size since the last ANALYZE gets roughly doubled row estimates. This scaling keeps total row counts reasonable between ANALYZE runs, but it cannot update the distribution of values.

Statistics on inheritance and partitions

For partitioned tables, each partition has its own statistics gathered by autovacuum, and the parent has statistics for the whole hierarchy, which autovacuum does not gather automatically, since the parent holds no rows itself. Queries that cannot prune partitions use the parent statistics for some estimates, so running ANALYZE on the partitioned parent periodically, through a scheduled job, avoids estimates based on missing or ancient parent statistics. This is a commonly missed maintenance step.

Who runs ANALYZE

Autovacuum runs ANALYZE on a table when the number of rows inserted, updated or deleted since the last analyze exceeds autovacuum_analyze_threshold plus autovacuum_analyze_scale_factor times reltuples, by default 50 plus 10 percent. Manual ANALYZE is needed after bulk loads, after creating expression indexes, for partitioned parents and for temporary tables, which autovacuum never touches. pg_stat_user_tables shows last_analyze and last_autoanalyze, the first places to look when estimates seem wrong.

Inspecting statistics

Querying pg_stats for a table and column shows exactly what the planner knows: the most common values and frequencies, the histogram and n_distinct. Comparing them with the real distribution, from a GROUP BY count on the column, reveals whether the problem is a stale sample, a target too low to capture the skew, or an n_distinct estimate far from reality. Reading pg_stats is the most direct way to understand a bad estimate.

How the statistics target scales the sample

The sample size is 300 times the largest statistics target among the columns being analyzed, so raising the target on a single column to 1000 makes ANALYZE of that table read 300000 rows instead of 30000. This is why per column targets should be raised only where needed: one high target makes the whole table analysis more expensive, though the extra statistics are kept only for that column.

Statistics and privileges

pg_statistic is readable only by superusers, since histograms and common values reveal data. The pg_stats view shows statistics only for columns the current user can read. Developers debugging plans need SELECT privilege on the tables involved to see their statistics, which is worth arranging in staging environments where plan analysis happens.

Statistics after upgrades and restores

Before version 18, a logical dump and restore carried data but no statistics, so the restored database planned with defaults until ANALYZE ran; version 18 added options to pg_dump and pg_restore to carry optimizer statistics as well. pg_upgrade historically did not carry statistics either, and version 18 changed this so optimizer statistics are preserved, avoiding a period of bad plans after upgrading. In older versions, running vacuumdb with analyze in stages, which builds coarse statistics quickly and refines them, is the standard step right after an upgrade or restore.

Statistics on temporary tables

Temporary tables are never analyzed by autovacuum, because autovacuum processes cannot see other sessions temporary data. A session that fills a temporary table and joins it with large tables gets plans based on default estimates, often assuming the temporary table is small. Running ANALYZE on the temporary table after filling it is a simple and frequently forgotten step.

When statistics are enough

For most single table queries on analyzed columns, statistics give estimates within a small factor, which is all the planner needs to pick well. Bad plans concentrate in a few situations: stale statistics after bulk changes, skew beyond the common values list, correlated columns, expressions and parameters. Knowing these situations lets you check the likely causes first.

Know what the planner knows

ANALYZE samples 300 times the statistics target rows and stores null fraction, width, distinct count, most common values, a histogram and correlation per column. Check last_autoanalyze, read pg_stats when estimates look wrong, analyze after bulk loads, and analyze partitioned parents on a schedule.