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
| Item | Description |
|---|---|
| Commands that collect | ANALYZE [table [(column)]], VACUUM ANALYZE |
| Sample size | 300 × 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 size | Up to statistics_target entries each (default 100) |
| Auto ANALYZE | autovacuum runs it when changed rows exceed autovacuum_analyze_threshold (50) + autovacuum_analyze_scale_factor (0.1) × reltuples |
| Table size | The 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-column | CREATE STATISTICS … (ndistinct, dependencies, mcv) (10+, mcv is 12+) |
| Freezing statistics | No feature. Turn off autovacuum per table, or set n_distinct directly |
| Sandbox | Collected 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';
| Column | Meaning |
|---|---|
null_frac | Fraction of NULLs |
avg_width | Average width (bytes) |
n_distinct | Number 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_freqs | The most common values and each one's frequency (MCV) |
histogram_bounds | Boundaries that split the remaining values (excluding the MCVs) into equal-count buckets |
correlation | Correlation 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.
| Column | n_distinct | MCV (frequency) | correlation |
|---|---|---|---|
customers.grade | 3 | NORMAL 0.901, GOLD 0.0895, VIP 0.0097 | 0.82 |
orders.status | 3 | DONE 0.901, PAID 0.0691, CANCELED 0.0300 | 0.82 |
orders.cust_id | 72,216 | 100 customers, IDs 1 to 100 (0.0006 to 0.0015 each) | 0.003 |
orders.ord_id, orders.ord_dt | -1 | None (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_idis 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_idandord_dtmeans the insertion order is the date order. An index scan over a date range is costed cheaply.
Row Count Estimation Rules
| Condition | Estimate |
|---|---|
col = constant, constant is in the MCV | That value's frequency |
col = constant, not in the MCV | (1 − sum of MCV frequencies − null_frac) ÷ (n_distinct − MCV count) |
col < constant | Position 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) > constant | Default 0.3333 |
condition1 AND condition2 | Product of selectivities (independence assumption). Adjusted if extended statistics dependencies or mcv exist |
Equality join a.x = b.y | Computed by matching the MCVs of both sides; the rest uses 1 ÷ max(n_distinct) |
Parameterized NL inner x = outer.value | The 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;
| Situation | Method |
|---|---|
| Skewed values do not all fit in the MCV | Enlarge the MCV size with SET STATISTICS |
n_distinct is far off | SET (n_distinct = …) |
Columns in an AND condition are correlated | CREATE STATISTICS … (dependencies, mcv) |
| Estimate for an expression condition is the default | Expression index (the index collects statistics on the expression) or expression statistics (14+) |
| Bad plan right after a bulk load | Run 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
| Item | PostgreSQL | Oracle | SQL Server |
|---|---|---|---|
| Distribution | MCV + histogram on every column | Histogram only on skewed columns used in conditions (SIZE AUTO) | Histogram of up to 200 steps on the first column of a statistics object |
| Sample | 30,000 rows (target 100) | Reads everything, NDV is approximate | Automatic by table size, or FULLSCAN |
| Sort correlation | correlation | CLUSTERING_FACTOR | (The clustered index is the table order) |
| Correlation adjustment | CREATE STATISTICS | Column group statistics | Density vector of multi-column statistics |
| Freezing | None | LOCK_TABLE_STATS | NORECOMPUTE |
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.