Sub topic 3
Sampling and default_statistics_target
This chapter assumes you can create tables, run ANALYZE, and read EXPLAIN output. It also assumes you know what pg_stats contains from the earlier chapters.
PostgreSQL does not read every row when it runs ANALYZE. It reads a random sample. The sample size comes from default_statistics_target, which defaults to 100. For each table, ANALYZE samples about 300 times the target, so 30,000 rows at the default. A larger sample gives better estimates for skewed data, but ANALYZE takes longer.
The target also controls how many most common values (MCVs) and histogram buckets PostgreSQL keeps for each column. Valid values range from 1 to 10000.
Raising the statistics target for one column
Raise the target for a single column when its values are unevenly spread and the planner keeps misjudging how many rows match a filter. Changing the global setting affects every column, so a per-column change is usually the better choice.
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500;
ANALYZE orders;The new target takes effect only after the next ANALYZE.
Extended statistics for correlated columns
The planner assumes that columns are independent. When two columns depend on each other, such as a city and its zip code, this assumption produces large misestimates. CREATE STATISTICS records the relationship.
CREATE STATISTICS addresses_city_zip (dependencies, ndistinct)
ON city, zip FROM addresses;
ANALYZE addresses;A workflow for diagnosing bad estimates
Follow these steps when a plan looks wrong:
- Run
EXPLAIN (ANALYZE)and compare estimated and actual rows at each node. - Check
last_analyzeandn_mod_since_analyzeinpg_stat_user_tables. - Read
pg_statsfor the filtered columns. - Raise the column's statistics target, or create extended statistics, then run
ANALYZE.
Special cases: partitioned tables, temporary tables, stale statistics
Autovacuum does not analyze partitioned parent tables, so run ANALYZE on the parent yourself after loading partitions. Autovacuum also skips temporary tables, so analyze those manually inside the session that uses them.
After a bulk load or a large delete, statistics go stale. Run ANALYZE right away rather than waiting for autovacuum.
ANALYZE measurements;Do not assume ANALYZE has run on a table you just loaded. Check last_analyze first.
Exercise
A query filters on customer_id, and EXPLAIN ANALYZE shows the planner estimated 12 rows where 9,000 matched. The table was analyzed an hour ago and has had no large changes since. Which change would you make first, and why?
Show answer
Raise the statistics target for customer_id with ALTER COLUMN ... SET STATISTICS, then run ANALYZE. The table is fresh, so stale statistics are not the cause. The column's distribution is the likely problem, and a per-column target addresses it without changing every other column.