Video in progress
The planner expected 10 rows and chose a Nested Loop, but 2 million rows actually came back. What is the cause, and what do you do?
The planner estimates the row count from statistics. If the statistics are stale, the columns are correlated, or the distribution is skewed, the estimate can be badly wrong and the wrong join type gets chosen. First ANALYZE, then raise the statistics precision or use extended statistics.
📖 Answer
The statistics live in pg_stats: for each column, the most common values, a histogram, the NULL fraction, the number of distinct values. Autoanalyze refreshes it when 10% of the table has changed.
Typical causes and fixes:
1. Stale statistics. A query ran right after a big import, before autoanalyze got to it. After a batch load, call ANALYZE orders; yourself.
2. Skewed distribution. 1000 customers, but one corporate customer has half the orders. The default sample of 100 may not catch this:
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 1000;
ANALYZE orders;
3. Correlated columns. city = 'Toshkent' AND region = 'Toshkent'. The planner treats them as independent, multiplies the probabilities, and estimates far too few rows:
CREATE STATISTICS st_addr (dependencies, ndistinct) ON city, region FROM address;
ANALYZE address;
4. A condition on a function. WHERE date_trunc('day', created_at) = ...: the planner doesn't know the selectivity. If you create an expression index, statistics are collected for it too.
To check: in EXPLAIN ANALYZE I read from the bottom up and find the first node where rows and actual rows differ sharply. The problem usually starts there, and the nodes above are just the consequence.
I don't change settings like enable_nestloop = off globally on prod; they're for diagnostics only.
Sign up to mark studied questions and save your progress.