Sub topic 10
Raising the statistics target for one column
This chapter assumes you can read EXPLAIN (ANALYZE) output and can query pg_stats. It also assumes you know that ANALYZE samples a table and stores most common values (MCVs) and a histogram for each column. Here you will learn what the statistics target controls, how to raise it for a single column, and how to tell whether the change helped.
What the target controls
The statistics target is a per-column number that sets how much detail ANALYZE keeps. It is set globally by default_statistics_target, which is 100 unless you change it. A single number controls three things:
- Most common values.
ANALYZEstores up to target entries inmost_common_vals, with matching frequencies inmost_common_freqs. - Histogram buckets.
ANALYZEstores up to target buckets, which is target + 1 entries inhistogram_bounds. The histogram describes the values that did not make the MCV list. - Sample size.
ANALYZEreads about 300 × target rows. At the default of 100 that is 30,000 rows, however large the table is.
| Target | Rows sampled | Max MCV entries | Max histogram buckets |
|---|---|---|---|
| 100 (default) | 30,000 | 100 | 100 |
| 500 | 150,000 | 500 | 500 |
| 1000 | 300,000 | 1000 | 1000 |
| 10000 (maximum) | 3,000,000 | 10000 | 10000 |
The limits are maximums. A column with only 12 distinct values never produces more than 12 MCV entries, whatever the target. If the table has fewer rows than 300 × target, ANALYZE reads every row, so raising the target on a small table changes nothing.
When a higher target helps
The default of 100 is enough for most columns. A higher target helps when the distribution has detail that 100 entries cannot hold. Typical cases:
- A long tail of semi-common values. Suppose 3,000 customers each own between 0.01% and 2% of the rows. Only about 100 of them fit in the MCV list. The planner estimates the rest from the histogram, which is coarse for individual values.
- Range predicates on skewed data. Each of 100 histogram buckets holds roughly 1% of the non-MCV rows. A range that covers a fraction of one bucket is estimated by interpolation. Interpolation is inaccurate when the data inside the bucket is lumpy.
- Joins on a skewed column. The planner compares the MCV lists of both sides of a join. Longer lists on both sides give a better join row estimate.
A higher target does not help when:
- Two columns are correlated. Use extended statistics instead.
- The statistics are stale. Run
ANALYZEor tune autoanalyze. - The filter uses an expression such as
lower(email). The planner has no statistics for the expression unless an expression index or extended statistics on that expression exists. - The estimate that is wrong is
n_distinct. A bigger sample helps only slowly with distinct counts on large tables. For that case, see then_distinctoverride described later.
Worked example
This table has a heavily skewed account_id. Squaring random() four times over pushes most rows toward small ids.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_id int NOT NULL
);
INSERT INTO events (account_id)
SELECT (1 + floor(power(random(), 4) * 5000))::int
FROM generate_series(1, 1000000);
ANALYZE events;Check how many MCV entries and histogram entries ANALYZE kept at the default target:
SELECT attname,
n_distinct,
array_length(most_common_vals::text::int[], 1) AS mcv_entries,
array_length(histogram_bounds::text::int[], 1) AS histogram_entries
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'events'
AND attname = 'account_id';The ::text::int[] cast converts the anyarray columns into something array_length can use. With the default target you should see at most 100 MCV entries and 101 histogram entries.
Now compare the estimate with reality for a value in the tail. Pick a value that is not in the MCV list, such as 1500:
EXPLAIN (ANALYZE)
SELECT * FROM events WHERE account_id = 1500;Look at rows= (the estimate) and actual ... rows= on the scan node. For a value outside the MCV list, the estimate is the average frequency of the non-MCV values. The actual count can be quite different.
Raise the target for that one column and re-analyze:
ALTER TABLE events ALTER COLUMN account_id SET STATISTICS 1000;
ANALYZE events;Run the two queries again. The MCV list now holds up to 1,000 values, so many more tail values have their own measured frequency. Your exact numbers will differ from run to run, because ANALYZE samples randomly. The direction of the change is what to look for: a smaller gap between estimated and actual rows for the values that moved into the MCV list.
Checking and resetting the target
The target is stored in pg_attribute. pg_stats does not show it.
SELECT attname, attstattarget
FROM pg_attribute
WHERE attrelid = 'events'::regclass
AND attname = 'account_id';A column that uses the global default shows -1 in PostgreSQL 16 and earlier, and NULL in PostgreSQL 17 and later. To return a column to the default:
ALTER TABLE events ALTER COLUMN account_id SET STATISTICS -1;
ANALYZE events;Setting the target to 0 turns off statistics collection for the column. The planner then falls back to fixed default selectivities for it. This is almost never what you want, except for a column you never filter or join on in a very wide table.
You can also change the target for a whole session without touching the table definition:
SET default_statistics_target = 500;
ANALYZE orders;This affects only columns without their own setting, and only for that ANALYZE run. Autovacuum does not see your session setting, so the next autoanalyze goes back to the stored targets. To make a change persistent, either set the per-column value or change default_statistics_target in the server configuration.
What a larger target costs
A larger target costs something at three points.
- ANALYZE time and I/O. The sample size is 300 × the largest target among the columns being analyzed. Raising one column to 1000 therefore makes
ANALYZEread 300,000 rows for the whole table, even though the other columns still keep only 100 entries each. On a wide table that is analyzed often, this adds up. - Catalog size. Each column's MCV list and histogram are stored in
pg_statistic. Large lists on many columns make the catalog bigger and the cached entries heavier. - Planning time. The planner scans MCV lists when it estimates a filter, and it compares two MCV lists when it estimates an equality join. A 10,000-entry list on both sides of a join takes noticeably longer to process than a 100-entry list. The cost is paid on every planning, so it matters most for short queries that run many times per second.
Values wider than 1,024 bytes are left out of the MCV list and histogram entirely. For long text columns, raising the target will not capture those values.
A practical approach is to move in steps, such as 100 → 250 → 500 → 1000. After each step, run ANALYZE and check the estimate. Stop when the estimate is good enough that the planner picks the right plan. Going to 10000 is rarely justified.
The n_distinct override
If the problem is the distinct count and a bigger sample does not fix it, you can set the value by hand:
ALTER TABLE events ALTER COLUMN account_id SET (n_distinct = 5000);
ANALYZE events;A positive number is an absolute count. A negative number between -1 and 0 is a fraction of the row count, so -0.5 means "half as many distinct values as rows", and it scales as the table grows. Use this only when you know the true number and it is stable.
Common mistakes
- Raising the target on every column. This slows
ANALYZEand planning for little gain. Raise it only for columns that show a misestimate in a query you care about. - Forgetting
ANALYZE. Covered above. The setting alone changes nothing. - Judging by one run. Sampling is random, so estimates differ slightly between runs. Check a few runs before concluding that a change worked.
- Expecting it to fix correlated columns. Each column's statistics are independent. A larger target will not tell the planner that
cityandzipmove together.
Exercise
You run ALTER TABLE events ALTER COLUMN account_id SET STATISTICS 1000 and then re-run EXPLAIN (ANALYZE) on a query filtering that column. The estimated rows are identical to before. Name two possible reasons.
Show answer
The most likely reason is that ANALYZE has not run since the change, so pg_stats still holds the old MCV list and histogram. A second reason is that the table has so few rows (fewer than 300 × the old target) that ANALYZE already read every row, or that the column has fewer distinct values than the old target, so the lists were already complete. A third possibility is that the misestimate comes from something a larger target cannot fix, such as correlated columns or a filter on an expression.
Exercise
Table t has columns a and b. You set the target of a to 2000 and leave b at the default of 100, then run ANALYZE t. How many rows does ANALYZE sample, and what is the largest number of MCV entries it can store for b?
Show answer
ANALYZE samples about 300 × 2000 = 600,000 rows, because the sample size follows the largest target among the table's columns. Column b can still store at most 100 MCV entries, because its own target is 100.