Sub topic 1
Why the planner needs statistics
Prerequisites
This chapter assumes you can do the following:
- Write basic SQL:
SELECT,WHERE,JOIN, andCREATE TABLE. - Describe at a conceptual level what an index is and why it can speed up a lookup.
- Run
psqland read simpleEXPLAINoutput, such as a node name and itscost=androws=values.
You do not need to know how ANALYZE works yet. The rest of this tutorial covers it. This chapter explains why it exists.
The planner chooses among many plans
SQL says what result you want. It does not say how to compute it. For one query, PostgreSQL can usually build many valid plans:
- Read the whole table with a sequential scan, or use an index.
- Join two tables with a nested loop, a hash join, or a merge join.
- Join a set of tables in many different orders.
All of these plans return the same rows. Their running times can differ by factors of thousands. The planner is the part of PostgreSQL that picks one plan before execution starts. It does not run the candidates. It predicts what each one would cost and picks the cheapest.
This design is called cost-based planning. Each plan node gets a cost number in arbitrary units. The units are loosely based on the cost of reading one disk page sequentially, which defaults to 1.0 (seq_page_cost). The cost of a plan is the sum of the costs of its nodes.
Costs depend on row counts
A node's cost is mostly a function of how many rows and pages it must handle. Here is a rough summary of how the common operations behave:
| Operation | What drives its cost | Why row count matters |
|---|---|---|
| Sequential scan | Pages in the table, plus a small CPU charge per row | Cost is fixed no matter how many rows match the filter |
| Index scan | Index pages plus random heap page fetches | Cost grows with the number of matching rows |
| Nested loop join | Outer rows times the cost of one inner lookup | Cheap for few outer rows, ruinous for many |
| Hash join | Building a hash table from one input, then probing it | Memory use depends on the build side's row count |
| Sort | Roughly n log n comparisons | Whether it fits in `work_mem` or spills to disk depends on row count |
The pattern is that nearly every decision turns on the number of rows a step will produce. This is called the cardinality estimate. The planner needs it for the table scans, and it also needs it for every join and filter above them. Each node's output estimate becomes the input estimate of the node above it.
Where the estimates come from
The planner cannot count rows by running the query, because planning has to be fast. So it uses statistics: summaries of each table's data that were collected earlier and stored in the system catalogs. The planner looks up these summaries and combines them with the query's conditions.
For a filter such as WHERE status = 'pending', the planner needs a selectivity. Selectivity is the fraction of the table's rows that the condition is expected to match. The estimated row count is:
estimated rows = total rows in table x selectivityTwo inputs are needed:
- The total number of rows. This is stored in
pg_class. - The selectivity of each condition. This is derived from per-column statistics stored in
pg_statistic, which thepg_statsview presents in a readable form.
The ANALYZE command collects these. Later chapters cover how it works and how to read what it stores. The point for now is that without these numbers, the planner would have to guess.
A worked example: one query, two plans
The following example makes the dependency visible. It creates a table where one value is rare and another is very common. The setup is the same table used throughout this tutorial.
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;About 95% of the rows are 'shipped' and about 5% are 'pending'. Now create an index on status and ask the planner about each value:
CREATE INDEX orders_status_idx ON orders (status);
EXPLAIN SELECT * FROM orders WHERE status = 'pending';
EXPLAIN SELECT * FROM orders WHERE status = 'shipped';On a typical installation, the first query shows a bitmap or index scan with an estimated row count near 5,000. The second shows a sequential scan with an estimated row count near 95,000. The exact numbers and node types vary with your version and settings. The shape of the result is the point.
The planner picks different plans for the same column because it knows the two values have different selectivity. Fetching 5,000 rows through an index touches a small part of the table. Fetching 95,000 rows through an index would mean visiting almost every page in random order, which is slower than reading the table straight through. The planner can only make this distinction because statistics told it how common each value is.
What happens when estimates are wrong
A wrong estimate does not cause a wrong answer. The query still returns correct rows. The cost is performance: the planner optimizes the wrong problem. Common failure patterns are:
- Underestimate leading to a nested loop. The planner expects 10 rows from one side of a join and chooses a nested loop. The real count is 2 million, so the inner side runs 2 million times.
- Overestimate leading to a sequential scan. The planner expects most of a table to match, so it skips a useful index and reads everything.
- Wrong join order. An early misestimate propagates upward. A join that looked small becomes the anchor of the plan, and the real intermediate result is huge.
- Memory misjudgment. A hash join or sort is sized for the estimated row count. If the real count is far larger, the operation spills to temporary files on disk.
Errors compound. Because each node's output feeds the node above it, a modest error at a scan can become a very large error several joins later. A plan with ten joins can start with estimates that are off by a factor of 3 and end with estimates off by a factor of thousands.
The opposite risk exists too. Stale statistics can mislead the planner just as much as missing ones. If a table was analyzed when it had 1,000 rows and now holds 10 million, the planner still believes the table is small.
What the planner does without statistics
If a table has never been analyzed, PostgreSQL does not give up. It uses a fallback. It looks at the table's current size in pages and assumes an average row width to estimate a row count. For conditions on columns, it applies fixed default selectivities. For example, it uses 0.5% for an equality condition and a similar small fraction for a range condition. These defaults are built into the planner and do not reflect your data.
You can see this effect with a fresh, never-analyzed table. The row estimate often looks like a round, generic figure rather than something that tracks the data. If you see this in a plan, treat it as a sign that statistics are missing or old.
The flow from data to plan
The following diagram shows how information moves from your data to a chosen plan, and where things can go wrong.
Limits of the model
Statistics are summaries, so they lose information. Three limits are worth knowing now, because later chapters address each of them:
- Sampling.
ANALYZEreads a random sample of the table, not every row. The sample is large enough for most columns, but rare values and unusual distributions can be missed. - Independence assumption. By default, the planner treats conditions on different columns as independent. It multiplies their selectivities. If two columns are correlated, such as city and postal code, this produces an estimate that is too low.
- Age. Statistics describe the table as it was at the last analyze. Large changes in the data since then make them less accurate.
None of these are bugs. They are trade-offs that keep planning fast. PostgreSQL gives you tools to adjust each one, and the remaining chapters cover them in order.
Summary of the key ideas
- The planner picks the cheapest plan by predicting costs, not by running candidates.
- Costs depend heavily on estimated row counts at every node.
- Row estimates come from statistics gathered by
ANALYZEand stored inpg_classandpg_statistic. - Wrong estimates produce correct but slow queries, and errors grow as they pass up through joins.
- Missing or stale statistics make the planner fall back on generic defaults or outdated numbers.
Exercise
A query joins orders to customers and filters orders with WHERE status = 'pending'. The planner expects 10 rows from the filter and chooses a nested loop join. At run time, the filter returns 5,000 rows. The query returns the right result but takes much longer than expected. Explain what went wrong and name one way the plan could change if the estimate had been accurate.
Show answer
The planner's row estimate for the filter was too low, which means the statistics did not reflect how common 'pending' really is. This can happen if the table was never analyzed, was analyzed long ago, or the column distribution is poorly captured. A nested loop runs its inner lookup once per outer row, so 5,000 outer rows means 5,000 inner lookups instead of 10. With an accurate estimate of about 5,000 rows, the planner would likely have chosen a hash join, which scans each input once. The result would be the same rows, produced faster.
Exercise
Why does the planner choose a sequential scan for WHERE status = 'shipped' even when an index on status exists, in the example table where about 95% of rows are 'shipped'?
Show answer
The planner estimates that about 95% of the rows match. Reading that many rows through an index means many random page fetches, touching nearly every page of the table. A sequential scan reads each page once in order, which costs less. The planner can make this choice only because statistics tell it how frequent the value is.