Sub topic 1
Why the Planner Needs Statistics
Prerequisites
This chapter assumes that you can write basic SQL with SELECT, WHERE, JOIN, and CREATE TABLE. You should also understand indexes at a conceptual level and be able to run psql and read simple EXPLAIN output.
The planner's job
When PostgreSQL receives a query, it must choose a query plan. A query plan is the sequence of operations PostgreSQL will use to produce the result. For example, it might scan every table row, use an index, join two tables, or sort intermediate results.
PostgreSQL uses a cost-based planner. The planner assigns an estimated cost to possible plans and normally chooses the plan with the lowest estimated cost. Cost is not a direct time measurement. It is a relative score based on work such as reading table pages, reading index pages, comparing values, and processing rows.
To compare plans, the planner needs to estimate how many rows each operation will produce. This number is called the row estimate.
For example, suppose a table contains one million orders:
- A filter that matches 500,000 rows may favor a sequential scan.
- A filter that matches 10 rows may favor an index scan.
- A join that produces 100 rows can use a different join strategy from one that produces 100 million rows.
The planner cannot run every possible plan first. It must make these predictions before execution.
Where the estimates come from
PostgreSQL stores statistics about tables and columns. The ANALYZE command collects these statistics by examining a sample of table rows. The planner then uses the statistics to estimate the selectivity of a condition. Selectivity is the fraction of rows that a condition is expected to match.
A simple example has a status column:
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 planner can learn that shipped is common and pending is rare. It can then estimate that this query returns far fewer rows than a query for shipped:
EXPLAIN
SELECT *
FROM orders
WHERE status = 'pending';The estimate is a prediction, not a promise. Statistics describe a sampled and possibly older view of the data.
How bad estimates cause bad plans
A row-count error can change the entire plan. If PostgreSQL estimates that a filter returns 10 rows, it may choose an index scan. If the filter actually returns 50,000 rows, repeatedly visiting the table through the index may cost more than reading the table once.
The opposite error also matters. If PostgreSQL expects many rows but the query returns only a few, it may choose a sequential scan or a hash-based operation when an index or nested-loop join would have been faster.
| Planner estimate | Actual result | Possible consequence |
|---|---|---|
| 10 rows | 50,000 rows | An index plan may perform poorly |
| 50,000 rows | 10 rows | A sequential scan may do unnecessary work |
| 1,000 rows | 1,000 rows | The chosen plan is more likely to fit the workload |
Following the planning process
The planner uses estimates at each plan node. A filter estimate affects the estimated input to a join. That join estimate affects the estimated cost of later sorting, grouping, or aggregation.
You can view the planned flow with a diagram:
To check whether the planner's predictions match reality, use EXPLAIN ANALYZE:
EXPLAIN (ANALYZE)
SELECT *
FROM orders
WHERE status = 'pending';EXPLAIN shows estimated rows for each node. EXPLAIN ANALYZE also runs the query and reports actual rows. A large, repeated difference between these values is evidence of a misestimate. Misestimates are clues that statistics may be stale, too coarse, or unable to describe relationships between columns.
Later chapters show how to inspect these statistics and refresh them with ANALYZE. The central idea is simple: PostgreSQL chooses plans using predictions, and statistics make those predictions possible.
Exercise
Why might PostgreSQL choose a poor index plan when the planner estimates 10 matching rows but the query actually returns 50,000?
Show answer
The planner expects only a few index lookups and therefore underestimates the work. With many actual matches, repeated index and table access may cost more than a sequential scan.