Sub topic 5
Most Common Values and Histograms
Prerequisites
This chapter assumes that you can run SELECT, WHERE, and EXPLAIN in PostgreSQL. You should also know that the cost-based planner chooses a query plan by comparing estimated costs. The planner needs statistics to estimate how many rows a condition will match.
Why value distributions matter
Suppose a table contains one million orders. If 95% have the status shipped and 5% have the status pending, these predicates do not have the same selectivity. Selectivity is the estimated fraction of rows that satisfies a condition.
The planner stores information about such distributions in pg_stats. ANALYZE collects a sample of table rows and updates these statistics.
Two important forms of column statistics are:
- A most common values list, or MCV list, records values that occur unusually often.
- A histogram describes the distribution of other values across ranges.
The planner combines these statistics with a query predicate to estimate its result size.
Reading MCV statistics
Create and populate a sample table:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id int NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders (customer_id, status)
SELECT (random() * 1000)::int,
CASE WHEN random() < 0.95 THEN 'shipped' ELSE 'pending' END
FROM generate_series(1, 100000);
ANALYZE orders;Inspect the statistics for status:
SELECT attname,
n_distinct,
most_common_vals,
most_common_freqs,
histogram_bounds
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname = 'status';The most_common_vals column contains values such as shipped and pending. The matching position in most_common_freqs gives each value's estimated frequency. For example, a frequency near 0.95 means that the planner expects about 95% of rows to have that value.
The exact output depends on the sample and the statistics target. Statistics are estimates, not a complete inventory of every value in the table.
Reading histograms
A histogram is useful when a column has many distinct values. PostgreSQL divides the non-MCV part of the sampled data into approximately equal-frequency ranges. The histogram_bounds array contains the boundaries of those ranges.
For example, inspect the numeric customer IDs:
SELECT attname,
n_distinct,
most_common_vals,
most_common_freqs,
histogram_bounds
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname = 'customer_id';If a value does not appear in the MCV list, the planner uses the histogram to estimate how many rows fall in the requested range. A predicate such as this can use the histogram:
EXPLAIN
SELECT *
FROM orders
WHERE customer_id BETWEEN 100 AND 200;For a uniformly distributed column, the planner can estimate the fraction of the histogram range covered by 100 through 200. For a skewed column, the estimate depends on where those values fall among the boundaries.
When PostgreSQL has an MCV list, the histogram generally describes the remaining values after the listed common values have been accounted for. This prevents a very frequent value from distorting estimates for the rest of the distribution.
Checking the estimate
Compare the planner's estimate with the actual result:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE status = 'pending';In the plan, rows= before execution is the estimate. The actual rows= value is what the executor observed. A small difference is normal. A large, repeated difference suggests that the MCV list does not capture the distribution well, or that the statistics are stale or too coarse.
You can refresh the statistics with:
ANALYZE orders;If a column has many distinct values or several important frequency peaks, a later chapter will show how to raise its per-column statistics target. That gives ANALYZE more room for MCV entries and histogram boundaries, at the cost of more analysis work and catalog storage.
Exercise
If most_common_vals reports pending with a frequency of 0.05, what does the planner expect from WHERE status = 'pending' on a table with 100,000 rows?
Show answer
It expects approximately 5,000 matching rows, although the actual count can differ because the statistic is based on a sample.