What Is a Database Query Planner? How Plans Are Chosen and Inspected
A query planner decides how a database will read and combine data for a SQL statement. The same SQL may use a sequential scan, an index scan, or a different join strategy depending on table size, value distribution, indexes, statistics, and settings. In PostgreSQL, `EXPLAIN` shows the selected plan; refreshed statistics can improve the estimates behind that choice. Plan cost is not elapsed time, and `EXPLAIN ANALYZE` actually executes the statement.
How does the planner process SQL?
PostgreSQL query processing broadly passes through parsing, rewriting, planning, and execution. The parser checks syntax and builds a query tree. The rewrite system can transform it according to rules, including expanding a view into its underlying tables. The planner/optimizer then considers alternative paths that produce the same result, estimates their costs, and selects a plan. Finally, the executor follows that plan to scan, filter, sort, aggregate, and join rows.
For a query that finds one customer’s orders, the planner may compare scanning the entire orders table with using an index to locate matching rows. For a join, it also chooses which input to read first and may select a nested-loop, hash, or merge join. The SQL text can stay unchanged while the best estimate changes as the table grows or its data distribution shifts.
How should you read a plan’s costs?
EXPLAIN displays a plan as a tree. Lower nodes usually scan tables; higher nodes combine or transform the rows through joins, sorting, or aggregation. A node’s rows value is an estimate of output rows, while cost is an estimate in planner units. Cost is not wall-clock seconds: it depends on configured cost parameters and models of I/O and CPU. It also does not fully include work such as formatting results and sending them to a client.
EXPLAIN
SELECT order_id, created_at
FROM orders
WHERE customer_id = 42;This shows the plan without running the statement. A Seq Scan is not automatically bad: if a table is small or a condition matches most rows, reading it sequentially can be cheaper. An Index Scan still has to fetch table rows after finding index entries, so it is not always better for queries returning many rows. Read estimated rows, filters, joins, sort steps, and the amount of data the query needs; do not judge performance from a node name alone.
How do statistics affect the choice?
To compare plans, the planner estimates how many rows match each condition. PostgreSQL’s ANALYZE collects table statistics that the planner uses for selectivity and row-count estimates. These are approximate, based on samples. If data has changed substantially or a large load has made the statistics stale, estimates can be wrong and lead to a poor plan.
Estimates can also miss relationships between columns. Suppose shipping country and shipping method are correlated. Treating the two filters as independent can misestimate how many orders match both. PostgreSQL can collect extended statistics for selected column groups with CREATE STATISTICS, then gather them with ANALYZE. It does not infer every useful combination automatically; investigate correlated columns when evidence suggests they are distorting estimates.
How can you inspect a plan safely?
Capture the actual slow or important SQL, parameter values, and relevant data size and distribution. Different parameter values can have different selectivity and plans.
Run PostgreSQL `EXPLAIN` and read scan, join, and sort nodes together with estimated row counts. Do not interpret planner cost as elapsed time.
If you need actual row counts and node timing, consider `EXPLAIN ANALYZE`, but know that it executes the statement. Even a read can impose load; `INSERT`, `UPDATE`, and `DELETE` can change data. Use a test environment or an appropriate rollback plan.
If estimated and actual rows differ substantially, check whether statistics are current, whether the data is skewed or correlated, and whether filters are applied as index conditions or later filters.
Gather evidence before changing planner settings. PostgreSQL documentation points to appropriate statistics and `ANALYZE` as ways to improve plan quality; configuration changes need validation against the workload and version.
Does the planner always choose the fastest plan?
The planner tries to choose the plan it estimates will have the lowest cost. Actual time also depends on cache state, concurrent load, I/O latency, result transfer, and other factors that the model cannot fully predict. Statistics and costs are approximations, and complex queries may be planned from a bounded set of alternatives rather than exhaustive search. A plan is useful diagnostic evidence, not proof that it is always optimal. Observe representative parameters and real workloads, then recheck after a change.
Sources and scope
[PostgreSQL 18: The Path of a Query](https://www.postgresql.org/docs/18/query-path.html)
[PostgreSQL 18: Using EXPLAIN and plan costs](https://www.postgresql.org/docs/18/using-explain.html)
[PostgreSQL 18: Statistics Used by the Planner](https://www.postgresql.org/docs/18/planner-stats.html)
[PostgreSQL 18: ANALYZE command](https://www.postgresql.org/docs/18/sql-analyze.html)
The PostgreSQL 18 documentation was checked on 2026-11-22. Processing stages, EXPLAIN output, and statistics behavior described here are PostgreSQL-specific. The SQL is illustrative and was not run. The effects of EXPLAIN ANALYZE depend on the statement and environment.