Sub topic 1
Why the Planner Needs Statistics
Prerequisites
This chapter assumes you know basic SQL (SELECT, WHERE, CREATE TABLE), can run psql, and can read simple EXPLAIN output. You should also know that an index is a structure that speeds up lookups.
Why the planner needs statistics
The PostgreSQL planner decides how to run each query. It gives each candidate plan a cost, and that cost depends on how many rows each step will produce. The planner cannot count those rows before it runs the query, so it estimates them from statistics. A bad estimate can make an expensive plan look cheap. If the planner expects 10 rows but gets 500,000, it may choose a nested loop join where a hash join would finish much faster.
Collecting statistics with ANALYZE
ANALYZE is a command that reads a random sample of a table and stores what it finds. Run it after loading data or making large changes:
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;What pg_class knows: reltuples and relpages
pg_class is a system catalog, a built-in table that lists tables, indexes, and other relations. Two of its columns matter here. reltuples is the estimated row count. relpages is the number of 8 KB disk pages the table uses.
SELECT relname, reltuples, relpages
FROM pg_class
WHERE relname = 'orders';These numbers describe the whole table. They say nothing about how values are spread across the rows.
Reading column statistics in pg_stats
pgstats is a view that holds statistics for each column. For status, nullfrac gives the fraction of NULL values, and ndistinct gives the number of distinct values. mostcommonvals and mostcommon_freqs list the frequent values and their share of rows. A frequency of 0.95 for 'shipped' tells the planner that a filter for 'pending' keeps about 5 percent of rows.
SELECT attname, null_frac, n_distinct, most_common_vals, most_common_freqs
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'orders'
AND attname = 'status';Exercise
After running ANALYZE on orders, which view would you query to find the share of rows where status is 'pending', and which column would you read?
Show answer
Query pgstats and read mostcommon_freqs for the status column. The 'pending' value's frequency gives its share of rows, or 1 minus the 'shipped' frequency when only the two values exist.