Dataexecution planEXPLAINEXPLAIN ANALYZEquery planner

Query plan

Definition

A query plan is the tree of operations (scans, index lookups, joins, sorts) the query planner picks for a statement, based on table statistics and estimated cost.

In practice

The same SQL can run in microseconds or minutes depending on the plan. EXPLAIN shows the planner's choice and estimates; EXPLAIN (ANALYZE, BUFFERS) runs the query and shows actual rows, time and pages read per step. Look for sequential scans on selective filters, nested loops over many rows and large gaps between estimated and actual row counts.

Plans depend on statistics, so stale stats after a bulk load can flip a good plan into a bad one. Plans also change with data size, so test on realistic volumes. In production, tools such as pg_stat_statements and auto_explain find the expensive queries worth explaining.

Example

A plan estimates 10 rows for status = 'pending' but finds 2 million, so it picks a nested loop join that takes 40 s; running ANALYZE orders fixes the estimate and the plan.