SQL is declarative. You write what you want: "the names of customers in Oran who ordered this month". You do not write how to get it: which table to read first, whether to use an index, how to combine the rows. That decision belongs to the query planner, also called the query optimizer. The same query can run in milliseconds or minutes depending on the plan it picks.
This article explains what the planner does, how it estimates costs, why it sometimes chooses badly, and how to see its choices with EXPLAIN.
From SQL text to a plan
When you send a query, the database goes through a few stages:
- Parse. Check the syntax and build a tree that represents the query.
- Analyze and rewrite. Resolve table and column names, expand views, apply rewrite rules.
- Plan. Generate possible ways to execute the query, estimate the cost of each, and keep the cheapest.
- Execute. Run the chosen plan.
The plan is a tree of operators. Leaves read data (scans), inner nodes combine and transform it (joins, sorts, aggregates), and rows flow up to the root.
The choices the planner makes
For each table, an access path:
- Sequential scan: read every page of the table. Cheap per row, but reads everything.
- Index scan: walk an index to find matching rows, then fetch each one from the table. Good when few rows match.
- Index-only scan: answer from the index alone when it holds all the needed columns.
- Bitmap scan (PostgreSQL): collect matching row locations from one or more indexes, sort them by page, then read those pages in order. A middle ground for medium selectivity.
For each pair of inputs, a join algorithm: nested loop, hash join or merge join.
And a join order. With three tables there are a handful of orders; with ten, there are millions. Join order often matters more than anything else, because joining the two most selective inputs first keeps the intermediate results small.
Planners search this space with dynamic programming for a moderate number of tables, and switch to heuristics or randomized search when there are too many (PostgreSQL, for example, uses a genetic algorithm above a configurable number of tables).
How cost is estimated
The planner cannot run every plan to see which is fastest. It estimates.
Each operator gets a cost based on how many pages it reads and how many rows it processes. Configured constants weigh the parts: in PostgreSQL, seq_page_cost, random_page_cost, cpu_tuple_cost and others. Random page reads are by default treated as more expensive than sequential ones, which is why an index scan that touches many scattered pages can cost more than reading the whole table in order.
The key input is cardinality: how many rows each step will produce. For that, the planner relies on statistics, gathered by ANALYZE (run automatically by autovacuum in PostgreSQL, and by InnoDB's persistent statistics in MySQL):
- the number of rows and pages in each table,
- the number of distinct values in each column,
- the most common values and their frequencies,
- a histogram of the value distribution,
- the fraction of
NULLs.
From these, it estimates the selectivity of each condition. If city has 50 distinct values spread evenly, WHERE city = 'Oran' is estimated to match 1 row in 50. Combined with the row count, that gives an estimate of rows flowing out of the scan, which feeds the cost of everything above it.
A worked example
SELECT c.name, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.city = 'Oran' AND o.created_at >= '2026-11-01';
Suppose customers has 100,000 rows, orders has 5 million, and there are indexes on customers(city) and orders(customer_id).
The planner estimates that city = 'Oran' keeps about 2,000 customers. A good plan:
- Index scan on
customersusing thecityindex: about 2,000 rows. - Nested loop: for each of those customers, use the
orders(customer_id)index to fetch their orders. - Filter those orders by
created_at.
The alternative, a hash join that reads all 5 million orders, would be much more expensive here. But if the condition were on a city holding half the customers, the hash join would win, and the planner would switch. Same SQL, different plan, because the data is different.
Reading EXPLAIN
EXPLAIN ANALYZE
SELECT c.name, o.total FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.city = 'Oran';
PostgreSQL prints a tree. Each node shows the operator (Index Scan, Hash Join, Seq Scan...), its estimated cost, the estimated rows, and, with ANALYZE, the actual rows and time. MySQL has EXPLAIN and EXPLAIN ANALYZE too, with a different format.
The single most useful habit: compare estimated rows with actual rows. When the planner expected 10 rows and got 200,000, every decision above that node was made on wrong information. That is where slow plans usually come from.
Note that EXPLAIN ANALYZE really runs the query. Wrap data-changing statements in a transaction and roll back.
Why the planner gets it wrong
-
Stale statistics. A table that grew quickly since the last
ANALYZE. Run it after bulk loads. -
Correlated columns. The planner usually assumes conditions are independent.
city = 'Oran' AND postal_code = '31000'is estimated as two separate filters, which underestimates the result badly. PostgreSQL'sCREATE STATISTICScan record such dependencies. - Skewed data. One customer with a million orders while most have five.
- Opaque expressions. Functions on columns, or values only known at run time, give the planner little to estimate from.
- Generic plans for prepared statements, where a plan chosen for one parameter value is reused for very different ones.
What you can do
- Keep statistics fresh, and raise the statistics target on columns with skewed distributions.
- Add the index the plan needs, then check that it is used.
- Write conditions the planner can use: no functions on indexed columns unless you have an expression index, and matching types.
- Rewrite the query when needed, for example by aggregating before joining.
- Treat hints and planner settings (where your database supports them) as a last resort: they freeze a decision that may become wrong as data changes.
In short
- The planner generates candidate plans (access paths, join algorithms, join orders) and picks the one with the lowest estimated cost.
- Cost estimates depend on statistics about your data; cardinality estimates matter most.
-
EXPLAIN ANALYZEshows the plan; compare estimated and actual rows to find the problem. - Most bad plans come from wrong estimates, and most fixes are fresher statistics, a better index or a clearer query.
Originally published at abdeldjalilchougui.biz.
Top comments (1)
把“预估行数 vs 实际行数”作为第一排查点这个建议很实在,我之前也遇到过预估只有几十行、实际跑出几十万行的情况,根源基本都是统计信息过期。相关列那段也值得单独展开,city 和 postal_code 这种组合条件确实很容易让优化器低估结果集。