Sub topic 4
Reading column statistics in pg_stats
The planner never looks at your table's data when it plans a query. It reads a compact summary of each column and builds its row estimates from that. The summary is stored in the pg_statistic catalog, and the readable view over it is pg_stats. This chapter shows how to read every field in that view and what each one tells the planner.
This chapter assumes you can run psql, write basic SELECT queries with array functions, and have read the previous chapters on ANALYZE and pg_class. It reuses the orders table from those chapters.
What pg_stats is
ANALYZE writes one row per column into pg_statistic. That catalog is readable only by superusers, and its columns are stored in a format designed for the planner, not for people. pg_stats presents the same data in a readable form. It shows only the columns of tables you have permission to read, because the statistics contain real values from your data.
A column has no row in pg_stats until it has been analyzed. An empty result for a freshly loaded table means ANALYZE has not run yet. It does not mean the column has no statistics worth having.
If you need to recreate the sample table, run this setup:
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;The fields at a glance
Run this query to see the main fields for two columns:
SELECT attname, null_frac, n_distinct, most_common_vals,
most_common_freqs, histogram_bounds, correlation
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname IN ('status', 'customer_id');| Field | What it holds | Mainly used for |
|---|---|---|
| `null_frac` | Fraction of rows where the column is NULL | `IS NULL` and `IS NOT NULL` filters |
| `avg_width` | Average stored size of the column in bytes | Memory and sort cost estimates |
| `n_distinct` | Estimated number of distinct values | Equality on values not in the common list, `GROUP BY`, joins |
| `most_common_vals` | The most frequent values | Equality filters on popular values |
| `most_common_freqs` | The fraction of all rows for each common value | Same |
| `histogram_bounds` | Bucket boundaries for the remaining values | Range filters such as `<`, `>`, `BETWEEN` |
| `correlation` | How closely physical row order follows value order | Index scan cost |
null_frac and avg_width
null_frac is a fraction between 0 and 1 of rows that are NULL in this column. Both columns in the example are NOT NULL, so it is 0. For a nullable column with null_frac = 0.2, the planner estimates that WHERE col IS NULL returns 20% of the table.
avg_width is the average size in bytes of the column's values, measured on the sample. The planner uses it to estimate how much memory a sort or hash will need.
n_distinct and its sign
n_distinct has two forms, and mixing them up is a common mistake.
- A positive number is an absolute count.
n_distinct = 1001means about 1001 distinct values. - A negative number is a fraction of the row count, negated.
n_distinct = -0.4means the number of distinct values is about 40% of the number of rows.-1means every value is unique, which is what you see forid.
ANALYZE stores the negative form when it judges that the number of distinct values grows with the table. Concretely, it does this when the estimate is more than 10% of the rows. The planner multiplies the fraction by the current row count, so the estimate stays reasonable as the table grows without a new ANALYZE. Take a table with 100,000 rows and -0.4. The planner assumes 40,000 distinct values. If the table grows to 200,000 rows, it assumes 80,000.
For customer_id in the sample table, values run from 0 to 1000, so n_distinct is a positive number close to 1001. A count of about 1000 is far below 10% of 100,000 rows, so it is stored as an absolute count.
A wrong n_distinct is one of the most common causes of bad join and GROUP BY estimates. It is also the field most sensitive to sampling, because counting distinct values from a sample is inherently hard.
Most common values and their frequencies
most_common_vals and most_common_freqs are parallel arrays. The first frequency belongs to the first value, and so on. Each frequency is a fraction of all rows in the table, NULLs included. The pairs are sorted from most to least frequent.
For status, the output has this shape. The numbers vary from run to run because the data is random and ANALYZE samples:
most_common_vals | {shipped,pending}
most_common_freqs | {0.9503,0.0497}The array column has the polymorphic type anyarray, which makes it awkward to query directly. Cast it through text to turn it into rows:
SELECT t.val, t.freq
FROM pg_stats AS s,
unnest(s.most_common_vals::text::text[], s.most_common_freqs) AS t(val, freq)
WHERE s.schemaname = 'public'
AND s.tablename = 'orders'
AND s.attname = 'status';This returns one row per common value, which is easier to scan when the list is long.
Two rules help you read the list.
- A value must appear noticeably more often than average to earn a place. In a column where all values are about equally common, the list may be short or even empty, because no value stands out.
- The list holds at most as many entries as the statistics target, which is 100 by default.
When the column has few distinct values, as status does, the common-value list covers every value. The fractions then add up with null_frac to 1. In that case there is nothing left to describe, so histogram_bounds is NULL.
Histograms for everything else
histogram_bounds describes the values that are not in the common-value list. It is an array of boundaries that split those remaining values into buckets that each hold about the same number of rows. With the default target of 100, the array has up to 101 boundaries and 100 buckets. The buckets have equal population, not equal width. A dense region of values gets narrow buckets, and a sparse region gets wide ones.
For customer_id, histogram_bounds looks like {0,9,19,29,...,1000}. The planner reads this as roughly 1% of the non-common rows between each pair of neighbors.
Values wider than 1 kB are left out of both the common-value list and the histogram. They still count toward n_distinct and avg_width. If a large text column seems to have no useful statistics, this is a likely reason.
correlation
correlation is a number from -1 to 1. It compares the physical order of rows on disk with the sorted order of the column's values.
- Near 1 means rows are stored almost in ascending order of this column. The
idcolumn of an insert-only table is the typical case. - Near -1 means rows are stored in descending order.
- Near 0 means the physical order is unrelated to the values.
The planner uses this to price index scans. With high correlation, an index range scan reads neighboring heap pages in sequence and is cheap. With correlation near 0, each index entry can point to a different page, so the scan is expensive and the planner leans toward a bitmap or sequential scan. Check it like this:
SELECT attname, n_distinct, correlation
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname IN ('id', 'customer_id');Expect id to show n_distinct = -1 and correlation = 1, and customer_id to show a correlation close to 0. Correlation drifts as UPDATE and DELETE activity reshuffles where new rows land, so a column that was well ordered at load time may not be later.
Other things you may see
inherited: Parent tables in an inheritance tree can have two rows per column. One covers only the parent's own rows (inherited = false) and one covers the parent plus children (inherited = true). A partitioned table has only the second kind, because it holds no rows itself.- Array columns: For arrays and similar types,
most_common_elemsandelem_count_histogramdescribe the individual elements, which supports containment searches such as@>. - Expression indexes: Statistics for an indexed expression appear in
pg_statswith the index's name in thetablenamecolumn.
Common mistakes
- Treating the numbers as exact. The statistics come from a sample, so two
ANALYZEruns on the same data give slightly different frequencies. Differences of a few percent are normal. - Reading a negative
n_distinctas a count. Multiply it by the row count fromreltuplesfirst. - Forgetting that frequencies cover all rows. In a column with many NULLs, the common-value frequencies add up to
1 - null_fracat most, not to 1. - Expecting a histogram for a column with few distinct values. A NULL
histogram_boundsis correct there.
Exercise
A table has reltuples = 2000000. In pg_stats, one column shows n_distinct = -0.25. How many distinct values does the planner assume, and what would it assume after the table grows to 3,000,000 rows without a new ANALYZE?
Show answer
The planner multiplies the negated fraction by the row count: 0.25 × 2,000,000 = 500,000 distinct values. After growth to 3,000,000 rows it assumes 0.25 × 3,000,000 = 750,000 distinct values.
Exercise
For a nullable column, pg_stats shows null_frac = 0.1, most_common_vals = {a,b}, most_common_freqs = {0.6,0.3}, and histogram_bounds is NULL. What does this tell you about the column's contents, and why is the histogram empty?
Show answer
10% of rows are NULL, 60% are a, and 30% are b. These fractions add up to 1, so the column holds no other values. The histogram describes values outside the common-value list, and no such values exist, so histogram_bounds is NULL.