Sub topic 9
Sampling and default_statistics_target
This chapter assumes you can read pg_stats, including most common values (MCVs) and histogram bounds, and that you know ANALYZE fills them. Here you will learn how much data ANALYZE reads, what default_statistics_target changes, and what the setting costs.
ANALYZE reads a sample, not the table
ANALYZE does not scan every row of a large table. It reads a bounded random sample and computes all column statistics from that sample. Its work therefore stays roughly constant as the table grows, and every statistic is an estimate with sampling error.
The sample size comes from one formula:
sample rows = 300 × statistics targetWith the default target of 100, ANALYZE samples 30,000 rows. A table with 3,000 rows is read completely. A table with 300 million rows is read through a 30,000-row window, about 0.01% of it.
How the sample is taken
PostgreSQL samples in two stages, so that it does not have to read every page of a large table.
- It picks up to
300 × targetpages at random. If the table has fewer pages than that, it reads all of them. At the default target this threshold is 30,000 pages, roughly 235 MB with 8 kB pages. - From the rows on those pages, it keeps a random sample of
300 × targetrows using reservoir sampling. Reservoir sampling keeps a fixed-size sample from a stream of unknown length. Each row has an equal chance of ending up in it.
Dead rows are not part of the sample. ANALYZE also uses the pages it read to extrapolate reltuples for pg_class.
What default_statistics_target controls
The target sets three limits at once:
| Target | Sample rows | Max MCV entries | Max histogram buckets |
|---|---|---|---|
| 10 | 3,000 | 10 | 10 |
| 100 (default) | 30,000 | 100 | 100 |
| 1000 | 300,000 | 1000 | 1000 |
| 10000 (maximum) | 3,000,000 | 10000 | 10000 |
The allowed range is 1 to 10000. default_statistics_target applies to every column that has no setting of its own. A column with a per-column target uses that value instead. The next chapter covers per-column targets.
A larger target gives the planner a longer MCV list and a finer histogram. It also gives ANALYZE more rows to build them from, so the estimates are less noisy.
Two details are easy to miss:
- When ANALYZE processes a table, it samples enough rows for the column with the highest target. Raising the target on one column therefore enlarges the sample for the whole table. Other columns benefit from the bigger sample but keep their own limits on MCVs and buckets.
- If a column's distinct values all fit within the target, the MCV list holds all of them and
histogram_boundsis null. A small enum-like column often looks this way.
Seeing the effect
This experiment reuses the orders table from earlier in the tutorial. It changes the target for the current session only, re-analyzes, and counts the stored entries.
SHOW default_statistics_target;
SET default_statistics_target = 10;
ANALYZE VERBOSE orders;
SELECT attname,
array_length(most_common_vals::text::text[], 1) AS mcv_entries,
array_length(histogram_bounds::text::text[], 1) AS histogram_bounds
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname = 'customer_id';ANALYZE VERBOSE prints a line like this one. The numbers depend on your table:
INFO: "orders": scanned 735 of 735 pages, containing 100000 live rows and 0 dead rows; 3000 rows in sample, 100000 estimated total rowsThe line shows the sample size (3,000 rows, which is 300 × 10). It also shows that all pages were read, because the table is small, and how reltuples was derived. Now repeat with a larger target and compare:
SET default_statistics_target = 1000;
ANALYZE VERBOSE orders;
SELECT attname,
array_length(most_common_vals::text::text[], 1) AS mcv_entries,
array_length(histogram_bounds::text::text[], 1) AS histogram_bounds
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname = 'customer_id';
RESET default_statistics_target;
ANALYZE orders;The sample is now 300,000 rows. The table has only 100,000, so ANALYZE reads all of them and the statistics are exact. The RESET and final ANALYZE put the table back on the default target. If you skip them, the stored statistics keep the last values you computed.
Why 300 × target
The factor 300 comes from the research behind PostgreSQL's histogram code (Chaudhuri, Motwani and Narasayya, 1998). That work shows that a random sample of this size keeps histogram bucket errors within acceptable bounds, with high probability, whatever the table size. The relationship is why the sample does not need to grow with the table: bucket accuracy depends on the sample size and the number of buckets, not on the table's row count.
The guarantee covers histogram-style range estimates. Other statistics are less well served, as the next section explains.
What a sample cannot see
Sampling creates three recurring problems.
n_distinct on large tables. The number of distinct values is hard to estimate from a sample. A value that appears once in the table may be missed entirely. PostgreSQL uses the Haas-Stokes estimator, which can be off by large factors. For example, it may report 40,000 distinct values for a column that really has 4 million. Raising the target helps only slowly. You can override the estimate directly with ALTER TABLE ... ALTER COLUMN ... SET (n_distinct = N). That override is the usual fix for badly estimated GROUP BY and join row counts.
Rare values. A value with frequency far below 1/sample_rows is unlikely to appear in the sample. The planner then falls back on a generic estimate for values outside the MCV list, derived from the remaining non-MCV fraction and distinct count. For rare but important values, a larger target helps. Extended statistics or a partial index may also help, depending on the query.
Run-to-run variation. The sample is random, so two ANALYZE runs on a large, changing table can produce slightly different MCV frequencies and histogram bounds. A plan may flip between runs when two plans have similar costs. Tables small enough to be read fully do not have this problem.
The cost of larger targets
A bigger target is not free:
- ANALYZE time and memory. The sample grows linearly with the target, and sorting each column's values costs more. At 10000, ANALYZE samples 3 million rows per run, which is noticeable on wide tables.
- Planning time. The planner reads the MCV list and histogram of every column a query touches. Join estimation compares the MCV lists of both sides, which costs more than linear time in list length. Long lists on many frequently queried columns raise planning time for every query, including cheap ones.
- Storage. Statistics live in
pg_statistic. They are stored out of line and are small compared to user data, but a very large number of high-target columns adds up.
Choosing a target
Use these criteria in order:
- Start with the default. 100 is adequate for most columns.
- Prove a problem first. Raise the target only when
EXPLAIN (ANALYZE)shows a large gap between estimated and actual rows, andpg_statsshows that the MCV list or histogram does not capture the distribution. A skewed column with more than 100 important values, or a column with an uneven histogram, are typical cases. - Raise it on the column, not globally. A per-column target limits planning cost to the queries that need the detail.
- Move in steps. Try 250, 500, then 1000, and check the estimate after each re-analyze. Values above 1000 are rarely justified.
- Check it did not fix the wrong thing. If the issue is
n_distinct, correlated columns, or stale statistics, a larger target will not help. Use the matching fix.
Lowering the target can also be reasonable. A column that is never filtered on, such as a large text payload, can have a target of 1 or a low value to spare ANALYZE work.
Common errors
- Changing the setting but not re-analyzing. Statistics change only when ANALYZE runs. After a new target, run
ANALYZEon the table. - Setting a high target globally. Every column gets long MCV lists and histograms, and planning slows across the workload.
- Expecting exact results from a larger target. More sample rows reduce error. They do not remove it, and
n_distinctcan stay far off. - Reading one ANALYZE run as the truth. Compare estimates after two or three runs on a large table before concluding that a change helped.
Exercise
A table has 40 million rows and default_statistics_target is 100. How many rows does ANALYZE sample, what fraction of the table is that, and what happens to the sample size if one column of the table has a per-column target of 500?
Show answer
It samples 300 × 100 = 30,000 rows, which is 0.075% of 40 million rows. With a column target of 500, ANALYZE samples for the highest target among the columns: 300 × 500 = 150,000 rows, about 0.375% of the table. This enlarged sample is used for all columns of that table, though the other columns keep their own limits of 100 MCVs and 100 histogram buckets.
Exercise
After raising a column's target from 100 to 1000, pg_stats shows no change in most_common_vals or histogram_bounds. Give two likely reasons.
Show answer
First, ANALYZE has not run since the change, so the stored statistics are still the old ones. Second, the column may have few distinct values, so the existing MCV list and histogram already capture them. In that case a larger target has nothing more to record.