Statistics and histograms
Overview
Optimizers summarize data rather than count every possible predicate during planning. PostgreSQL collects null fractions, distinct-value estimates, most-common values and frequencies, histogram bounds and physical correlation. Histograms approximate distribution; most-common values are handled separately. Extended statistics can describe selected cross-column relationships. ANALYZE refreshes statistics; sampled estimates can be imperfect.
First example
SELECT stat FROM sqlite_stat1 WHERE idx='opt_status';Observed SQLite result (rows in JSON):
[ [ "100 50" ]]How it works
The fixture has 90 common and 10 rare orders. sqlite_stat1 records 100 50 for the status index: total entries and average entries per distinct leading key. This is neither a histogram nor a specific query estimate. Optional SQLite STAT4 depends on the build. The second query obtains exact frequencies by reading data, unlike statistics used at planning time.
Practical example
SELECT status,COUNT(*) FROM opt_order GROUP BY status ORDER BY status;Observed SQLite result (rows in JSON):
[ [ "common", 90 ], [ "rare", 10 ]]Practice and mistakes
Practice: count orders in amount bands 1–250, 251–500, 501–750 and 751–1000. Hint: CASE or integer arithmetic followed by GROUP BY. Expect 25 each. Compare this exact teaching histogram with PostgreSQL pg_stats; do not assume all histogram buckets have the same numeric width.
PostgreSQL 17 example — NOT RUN
BEGIN;SET LOCAL statement_timeout='10s';SET LOCAL lock_timeout='2s';CREATE TEMP TABLE opt_customer(id INTEGER PRIMARY KEY, name TEXT NOT NULL);INSERT INTO opt_customer VALUES(1,'Ada'),(2,'Reza'),(3,'Sara'),(4,'Mina');CREATE TEMP TABLE opt_order(id INTEGER PRIMARY KEY,customer_id INTEGER NOT NULL REFERENCES opt_customer(id),amount INTEGER NOT NULL,status TEXT NOT NULL,region TEXT NOT NULL);WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i<100)INSERT INTO opt_order SELECT i,1+(i%3),10*i,CASE WHEN i<=10 THEN 'rare' ELSE 'common' END,CASE WHEN i<=10 THEN 'east' ELSE 'west' END FROM n;CREATE INDEX opt_amount ON opt_order(amount);CREATE INDEX opt_status ON opt_order(status);CREATE INDEX opt_region ON opt_order(region);CREATE INDEX opt_customer_idx ON opt_order(customer_id);CREATE TEMP TABLE opt_line(id INTEGER PRIMARY KEY,order_id INTEGER NOT NULL REFERENCES opt_order(id));INSERT INTO opt_line VALUES(1,1),(2,1),(3,2),(4,42);CREATE INDEX opt_line_order ON opt_line(order_id);ANALYZE opt_order;ANALYZE opt_customer;ANALYZE opt_line;
SELECT attname,null_frac,n_distinct,most_common_vals,most_common_freqs,histogram_bounds,correlation FROM pg_stats WHERE schemaname LIKE 'pg_temp_%' AND tablename='opt_order' AND attname IN ('status','amount') ORDER BY attname;ROLLBACK;Expected result, not executed: "Inspect sampled statistics; no fixed histogram bounds asserted."