Cardinality estimation
Overview
Cardinality is the number of rows produced by a relation or plan node. Selectivity is the fraction satisfying a predicate in this lesson. A simplified independence model estimates N × p(A) × p(B) for two filters. With 100 rows and each filter matching 10%, it predicts one row. Correlated attributes can invalidate this model.
First example
SELECT COUNT(*) FROM opt_order WHERE status='rare' AND region='east';Observed SQLite result (rows in JSON):
[ [ 10 ]]How it works
All rare orders are east, so rare AND east returns ten, not one. rare AND west returns zero, although the independence estimate is nine. These are actual counts versus a hand-calculated model, not captured optimizer estimates. PostgreSQL extended statistics (dependencies, multivariate MCV and ndistinct) can improve selected estimates for columns in one table; they are not a universal fix for join estimation.
Practical example
SELECT COUNT(*) FROM opt_order WHERE status='rare' AND region='west';Observed SQLite result (rows in JSON):
[ [ 0 ]]Practice and mistakes
Practice: estimate and count common AND west. Hint: both marginal frequencies are 90%; independence predicts 81 rows. The actual count is 90. Explain why an underestimate early in a join tree may affect later join choice and memory decisions.
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;
EXPLAIN (ANALYZE,TIMING OFF) SELECT id FROM opt_order WHERE status='rare' AND region='east';CREATE STATISTICS opt71_stats (dependencies,mcv,ndistinct) ON status,region FROM opt_order;ANALYZE opt_order;EXPLAIN (ANALYZE,TIMING OFF) SELECT id FROM opt_order WHERE status='rare' AND region='east';ROLLBACK;Expected result, not executed: "Compare estimated rows before and after extended statistics; actual 10, improvement not guaranteed."