Sub topic 5
Most common values and histograms
This chapter assumes you can read pg_stats, you know what ANALYZE does, and you have seen EXPLAIN output with row estimates. The previous chapter covered the columns of pg_stats one at a time. This chapter covers two of them in depth: most_common_vals with most_common_freqs, and histogram_bounds. Together they describe how a column's values are spread. The next chapter shows how the planner turns them into row estimates.
Two tools for two kinds of data
A single number such as n_distinct cannot describe a column's distribution. The status column in the orders table has two values, and 95% of the rows hold one of them. The customer_id column has about a thousand values spread almost evenly. These columns need different descriptions.
ANALYZE keeps two structures for each column.
- Most common values (MCV) list. The values that occur most often, each stored with its frequency. Frequencies are fractions of all rows, so 0.95 means 95%.
- Histogram. A summary of the remaining values, which are too numerous or too evenly spread to list one by one.
The two structures do not overlap. The histogram describes only the values that did not make the MCV list. Nulls are counted separately in null_frac. The diagram shows how the rows of a column divide.
The three fractions add up to 1: null_frac, plus the sum of most_common_freqs, plus the share of rows the histogram covers. The planner relies on this identity.
Reading the MCV list
This chapter uses the orders table from the earlier chapters, built with the CREATE TABLE ... INSERT ... ANALYZE script. Start with the skewed column.
SELECT attname,
null_frac,
n_distinct,
most_common_vals::text AS mcv,
most_common_freqs AS mcf,
histogram_bounds::text AS hist
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname = 'status';Expect output close to this. The exact frequencies vary because the data is random and ANALYZE samples it.
attname | null_frac | n_distinct | mcv | mcf | hist
---------+-----------+------------+------------------+----------------+------
status | 0 | 2 | {shipped,pending} | {0.95,0.05} |most_common_vals and most_common_freqs are parallel arrays. The first value pairs with the first frequency, and so on, in descending order of frequency. The histogram_bounds column is empty here. Both values fit in the MCV list, so nothing is left over to summarize.
The most_common_vals column has the pseudo-type anyarray. Cast it to text to print it. To see value and frequency side by side, cast to text and then to text[], and unnest the two arrays together:
SELECT v.val, v.freq
FROM pg_stats AS s,
unnest(s.most_common_vals::text::text[], s.most_common_freqs) AS v(val, freq)
WHERE s.schemaname = 'public'
AND s.tablename = 'orders'
AND s.attname = 'status'
ORDER BY v.freq DESC;What gets into the list
ANALYZE does not put every value in the MCV list. It sorts the sample and keeps values that occur noticeably more often than the average value, up to the statistics target (100 by default). A column with 100,000 distinct values, all unique, gets no MCV list at all. For customer_id, where each value appears about 100 times, the list may hold a few values that came up more often in the sample, or it may be empty. A value that appears once in the sample is never listed.
The list is only as accurate as the sample. A frequency of 0.05 is an estimate from the sampled rows, not a count of the whole table.
Reading the histogram
For values outside the MCV list, ANALYZE builds an equi-depth histogram. It sorts the remaining sampled values and picks boundaries so that each bucket holds the same number of rows. With the default target of 100, there are up to 100 buckets, so histogram_bounds holds up to 101 boundary values.
SELECT h.i AS bound_no, h.b AS bound_value
FROM pg_stats AS s,
unnest(s.histogram_bounds::text::int[]) WITH ORDINALITY AS h(b, i)
WHERE s.schemaname = 'public'
AND s.tablename = 'orders'
AND s.attname = 'customer_id'
AND h.i <= 5
ORDER BY h.i;For uniformly random values from 0 to 1000, the first boundaries will be near 0, 10, 20, 30, 40. The buckets have equal depth, not equal width. In a region where values are dense, boundaries sit close together. In a sparse region they sit far apart. So the spacing of the boundaries shows where the data is concentrated.
Each bucket holds the same share of the rows the histogram covers. That share is:
bucket_fraction = (1 - null_frac - sum(most_common_freqs)) / number_of_bucketsWithin a bucket the planner assumes values are spread evenly and interpolates linearly. A query asking for the upper half of a bucket is estimated as half of that bucket's rows.
What each statistic answers
| Question in the WHERE clause | Statistic used |
|---|---|
| `col = value`, value is in the MCV list | The stored frequency for that value |
| `col = value`, value is not in the list | The leftover fraction divided by the number of non-listed distinct values |
| `col < value`, `col BETWEEN a AND b` | Matching MCV frequencies plus the histogram share for the range |
| `col IS NULL` | `null_frac` |
The table shows why both structures are needed. Equality on a rare value cannot use the histogram, because the buckets say nothing about single values. A range over a continuous column cannot use the MCV list alone, because most values are not listed. The next chapter works through the formulas in full.
Seeing the effect in EXPLAIN
An equality test on a listed value gets an accurate estimate straight from the frequency:
EXPLAIN (ANALYZE)
SELECT * FROM orders WHERE status = 'pending';The estimate is about 100,000 × 0.05, close to 5,000 rows, and the actual count is within a few percent. A value that is not in the list gets a very small estimate, usually one row:
EXPLAIN (ANALYZE)
SELECT * FROM orders WHERE status = 'cancelled';The planner knows from n_distinct and the MCV list that the list covers every distinct value, so it assumes this value is very rare.
A range test uses the histogram:
EXPLAIN (ANALYZE)
SELECT * FROM orders WHERE customer_id < 250;About a quarter of the values fall below 250, so the estimate is near 25,000 rows. The histogram makes this estimate close to the actual count.
Edge cases and limits
- No histogram. When every value fits in the MCV list, as with
status,histogram_boundsis null. Types without a less-than ordering, such asjsonorpoint, never get a histogram. - Large values.
ANALYZEignores values wider than 1 kB when it builds the MCV list and histogram. The statistics for a column of big text blobs describe only the smaller values. - Arrays. Array columns get
most_common_elemsandmost_common_elem_freqs, which describe the elements, not whole arrays. - Single columns only. Both structures describe one column. They carry no information about how two columns relate to each other. Correlated predicates need the extended statistics covered later.
- Rare values in a skewed column. If a value matters to your queries but is too rare to reach the sample, its estimate comes from the leftover average. The estimate can be far from the truth. A higher statistics target for that column often fixes this.
- Correlation. The
correlationcolumn is separate from both structures. It measures how closely physical row order matches value order, from -1 to 1. It affects index scan cost estimates, not row counts.
Exercise
A column has nullfrac = 0.10, and its mostcommon_freqs sum to 0.50. The histogram has 100 buckets. What fraction of the table's rows does each histogram bucket represent, and what fraction does the whole histogram cover?
Show answer
The histogram covers 1 - 0.10 - 0.50 = 0.40 of the table. Each of the 100 buckets holds 0.40 / 100 = 0.004, which is 0.4% of the rows.
Exercise
A query filters on status = 'pending', and pgstats shows `mostcommonvals = {shipped,pending} with mostcommonfreqs = {0.95,0.05} and a null histogrambounds`. Why is there no histogram, and does that hurt the estimate for this query?
Show answer
Both distinct values fit in the MCV list, so no values are left to summarize and ANALYZE stores no histogram. It does not hurt the estimate. An equality test on a listed value uses the stored frequency, 0.05, and never reads a histogram.