Sub topic 2
Most Common Values and Histograms
This chapter assumes you can run psql, write SELECT queries with WHERE, read a simple EXPLAIN plan, and that you have run ANALYZE on a table before.
Most common values and histograms
PostgreSQL stores two kinds of column statistics in the pg_stats view. The most common values (MCV) list holds frequent values and their fractions of the table. A histogram is a set of bucket boundaries that splits the remaining values into ranges of roughly equal row counts. The planner uses the MCV list for equality tests and the histogram for range tests.
SELECT attname, most_common_vals, most_common_freqs, histogram_bounds
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname = 'status';When a column has only a few distinct values, the MCV list covers them all, so histogram_bounds is NULL.
How statistics become row estimates
For WHERE status = 'pending', the planner looks for 'pending' in most_common_vals. If it finds the value, it uses the stored frequency as the selectivity, the fraction of rows that match. For a value missing from the list, it spreads the leftover probability across the other distinct values. For a range such as customer_id BETWEEN 100 AND 200, it counts the histogram buckets the range covers.
With 100,000 rows and a stored frequency of 0.05 for 'pending', the planner estimates 5,000 matching rows.
Spotting misestimates in EXPLAIN ANALYZE
EXPLAIN (ANALYZE)
SELECT * FROM orders WHERE status = 'pending';Each plan node shows two row counts: rows= inside the cost parentheses is the estimate, and actual ... rows= is the real count. A gap of about ten times or more usually means the statistics are stale or too coarse for that value.
Autoanalyze: when statistics refresh themselves
Autovacuum runs ANALYZE on a table after enough rows change. It does so when n_mod_since_analyze exceeds autovacuum_analyze_threshold (default 50) plus autovacuum_analyze_scale_factor (default 0.1) times the table's row count. For 100,000 rows, that is about 10,050 changed rows.
You can check the last analyze time and change count in pg_stat_user_tables. For a large table with rapid changes, lower the scale factor:
ALTER TABLE orders SET (autovacuum_analyze_scale_factor = 0.02);Exercise
A table has 2,000,000 rows and uses the default autoanalyze settings. How many modified rows trigger an automatic ANALYZE?
Show answer
50 + 0.1 × 2,000,000 = 200,050 modified rows.