PostgreSQL Planner Statistics

The PostgreSQL planner estimates the row count of each node from statistics alone, without executing the statement. Table size is in reltuples and relpages of pg_class, and column distributions are in pg_statistic (the human-readable view is pg_stats), which ANALYZE builds by reading a sample. PostgreSQL differs from Oracle's default behavior in that it builds per-value frequencies (MCV) and a histogram for every column. Because it computes from a sample, however, the number of distinct values (n_distinct) can be far off.

Summary

ItemDescription
Commands that collectANALYZE [table [(column)]], VACUUM ANALYZE
Sample size300 × default_statistics_target rows (default 100 → 30,000 rows). Per column with ALTER TABLE … ALTER COLUMN … SET STATISTICS n (up to 10,000)
MCV / histogram sizeUp to statistics_target entries each (default 100)
Auto ANALYZEautovacuum runs it when changed rows exceed autovacuum_analyze_threshold (50) + autovacuum_analyze_scale_factor (0.1) × reltuples
Table sizeThe planner recomputes the row count by multiplying reltuples ÷ relpages (row density) by the current actual page count. Size changes are reflected to some degree even without ANALYZE
Correlation and multi-columnCREATE STATISTICS … (ndistinct, dependencies, mcv) (10+, mcv is 12+)
Freezing statisticsNo feature. Turn off autovacuum per table, or set n_distinct directly
SandboxCollected once with VACUUM (ANALYZE, FREEZE) right after loading, and autovacuum is turned off for the table

Reading pg_stats

SELECT attname, null_frac, n_distinct, most_common_vals, most_common_freqs,
       array_length(histogram_bounds::text::text[], 1) AS hist_bounds, correlation
FROM pg_stats
WHERE schemaname = 'tune' AND tablename = 'orders';
ColumnMeaning
null_fracFraction of NULLs
avg_widthAverage width (bytes)
n_distinctNumber of distinct values. A negative value is a ratio to the row count (-1 = all distinct, -0.5 = half as many as rows)
most_common_vals / most_common_freqsThe most common values and each one's frequency (MCV)
histogram_boundsBoundaries that split the remaining values (excluding the MCVs) into equal-count buckets
correlationCorrelation between physical row order and value order (-1 to 1). Near 1, an index range read is close to sequential (Oracle's clustering factor)

Actual values in the sandbox.

Columnn_distinctMCV (frequency)correlation
customers.grade3NORMAL 0.901, GOLD 0.0895, VIP 0.00970.82
orders.status3DONE 0.901, PAID 0.0691, CANCELED 0.03000.82
orders.cust_id72,216100 customers, IDs 1 to 100 (0.0006 to 0.0015 each)0.003
orders.ord_id, orders.ord_dt-1None (101 histogram boundaries)1
  • Thanks to the MCV of grade, VIP is estimated as 0.0097 × 100,000 = 970 customers (actual 1,000). Oracle, which has no histogram here, sees the same condition as 33,333 customers (Oracle Optimizer Statistics).
  • The actual number of distinct values in orders.cust_id is 100,000, but it is estimated as 72,216. The total is extrapolated from the fraction of values that appear only once in the 30,000-row sample, so columns with many distinct values and few rows per value tend to come out low.
  • A correlation of 1 for ord_id and ord_dt means the insertion order is the date order. An index scan over a date range is costed cheaply.

Row Count Estimation Rules

ConditionEstimate
col = constant, constant is in the MCVThat value's frequency
col = constant, not in the MCV(1 − sum of MCV frequencies − null_frac) ÷ (n_distinct − MCV count)
col < constantPosition of the constant in the histogram (linear interpolation between boundaries) + frequencies of the matching MCV values
Expression f(col) = constant (no expression index or statistics)Default 0.005
Expression range f(col) > constantDefault 0.3333
condition1 AND condition2Product of selectivities (independence assumption). Adjusted if extended statistics dependencies or mcv exist
Equality join a.x = b.yComputed by matching the MCVs of both sides; the rest uses 1 ÷ max(n_distinct)
Parameterized NL inner x = outer.valueThe outer value is unknown, so 1 ÷ n_distinct (average)

The last row is the estimation error in Scenario 28. The high-volume customers 1 to 100 are in the MCV, but the NL inner lookup cannot know the outer customer number at planning time, so it computes with the average. It therefore treats the inner lookup as 1 row, while in reality it reads 543 rows per customer.

How to Change Statistics

-- Enlarge the sample and the MCV/histogram of one column (from the next ANALYZE)
ALTER TABLE orders ALTER COLUMN cust_id SET STATISTICS 1000;
ANALYZE orders (cust_id);

-- Set n_distinct directly (negative means ratio). Used from the next ANALYZE
ALTER TABLE orders ALTER COLUMN cust_id SET (n_distinct = 100000);

-- Correlation between columns: functional dependency, NDV of the combination, MCV of the combination
CREATE STATISTICS orders_cust_status (dependencies, ndistinct, mcv) ON cust_id, status FROM orders;
ANALYZE orders;
SELECT * FROM pg_stats_ext WHERE tablename = 'orders';

-- Statistics on an expression (14+)
CREATE STATISTICS orders_day ON (date_trunc('day', ord_dt)) FROM orders;
SituationMethod
Skewed values do not all fit in the MCVEnlarge the MCV size with SET STATISTICS
n_distinct is far offSET (n_distinct = …)
Columns in an AND condition are correlatedCREATE STATISTICS … (dependencies, mcv)
Estimate for an expression condition is the defaultExpression index (the index collects statistics on the expression) or expression statistics (14+)
Bad plan right after a bulk loadRun ANALYZE right after the load. autovacuum does not run immediately even when the threshold is exceeded

Checking the State

SELECT relname, n_live_tup, n_mod_since_analyze, last_analyze, last_autoanalyze
FROM pg_stat_user_tables WHERE schemaname = 'tune';

SELECT relname, reltuples::bigint, relpages FROM pg_class
WHERE relnamespace = 'tune'::regnamespace AND relkind IN ('r', 'i');

In the sandbox, orders has 2,000,000 rows, 18,752 pages, and n_mod_since_analyze is 0. Auto ANALYZE is off, so last_autoanalyze is empty.

Comparison with Other DBMSs

ItemPostgreSQLOracleSQL Server
DistributionMCV + histogram on every columnHistogram only on skewed columns used in conditions (SIZE AUTO)Histogram of up to 200 steps on the first column of a statistics object
Sample30,000 rows (target 100)Reads everything, NDV is approximateAutomatic by table size, or FULLSCAN
Sort correlationcorrelationCLUSTERING_FACTOR(The clustered index is the table order)
Correlation adjustmentCREATE STATISTICSColumn group statisticsDensity vector of multi-column statistics
FreezingNoneLOCK_TABLE_STATSNORECOMPUTE

Learn more: PostgreSQL Execution Plan Analysis, VACUUM.

NOTE Defaults and the kinds of extended statistics can differ by version. The values in this document were checked on PostgreSQL 17 in the sandbox.

Related pages