# Query plan

## What it is

A query plan describes the operations a database chooses to produce the result
of a query. SQL states the result in terms of rows, joins, filters and grouping.
The database can realise that result through several possible strategies. A plan
can show a table scan, an index lookup, a join between two inputs, or a step
that sorts and groups records. Operations feed work to one another, so the
diagram or text shows both the local operation and where its input comes from.

In PostgreSQL, EXPLAIN shows the planned operations with estimated costs and row
counts. These are estimates in units used by the planner. EXPLAIN ANALYZE
actually runs the statement and reports observed timing, rows and loops for the
operations. The options available to PostgreSQL can also report buffer activity
and other work. Compare estimates and observations to locate the first
surprising decision. An inaccurate row estimate early in the plan can affect the
join strategy or memory demand later.

For a query that asks for recent service tickets for a particular customer, one
possible plan scans an index to find the small set of relevant rows. When a
different parameter covers a large share of the table, a scan over the table can
make better use of storage and memory. The planner chooses under assumptions
about the data and available operations. What works well for one customer or
time range can perform differently for another.

## Why it matters

A latency measurement shows the experience, while a plan helps explain where
time was spent and which change is worth testing. A missing index is one
possible finding. Filtering after a join, unexpectedly many repetitions of a
search, spilling a sort to disk and poorly estimated filters point to different
changes. Use the plan alongside end-to-end timing and load measurements. An
individual operation can be inexpensive in isolation and dominate the request
when the database repeats it many times.

Plans also expose performance changes after an ordinary deployment. New data
distributions, stale statistics and changes to parameter usage can move a
frequent query onto a different plan. A test with evenly distributed fixture
data may never exercise the expensive version seen by a large customer. Collect
representative parameter groups and compare several executions. Pay particular
attention to queries involving skewed values, large date ranges and tables that
grow at different rates.

The best result depends on what the system needs to optimise. A plan that
returns the first screen quickly may matter more than one that produces every
possible matching row slightly faster. A scheduled export has different needs.
Changes such as a covering index can benefit certain reads while adding write
cost or storage. Agree on the performance measure before changing the query or
layout, and record the data size, parameter set and relevant settings so
somebody can repeat the experiment.

## What it looks like in practice

Start with a slow ticket search and capture the statement and representative
parameters without copying personal data into an incident report. Run an
estimated plan on an environment that resembles production. Make sure a query
you intend to run for measurements is safe to execute there. Compare the size of
intermediate inputs and note the order of joins and filters. On a suitable read
test, collect the estimated and actual rows, loops, buffer activity and elapsed
time, and record the response seen from the application.

Suppose a customer filter is estimated to match ten tickets but actually matches
fifty thousand. Work back from the first difference. Look at table statistics,
selectivity for the affected customer, correlation between customer and date,
and the form of the query. Then change one factor at a time and compare the
outcome with a small customer as well as the large one. Check both a
representative repeat and the effect on concurrent use. Use a separate
environment to investigate queries that could change data or generate
substantial load.

Our
[PostgreSQL optimisation case study](/portfolio/accelerated-postgresql-performance-by-10x/)
describes using EXPLAIN ANALYZE to find inefficient joins and subqueries
alongside indexing and partitioning work. It illustrates a reason to collect
evidence before choosing a fix. The ticket example gives a repeatable way to
investigate one type of bad estimate, so readers can apply the same diagnosis to
a query whose parameters they understand.

## Where it goes wrong

Executing a plan with analysis can have expensive or persistent effects. It runs
the statement, which can write data for a modifying query, lock resources or
call functions. Prefer safe read examples against representative non-production
data when learning the tool. If a live diagnostic is justified, bound its time
and scope, review the specific statement and database semantics, and determine
which possible effects a rollback can and cannot reverse.

A plan's costs are estimates expressed in planner units. Treating them as
measurements in milliseconds can lead to the wrong comparison. Actual timing can
also include measurement overhead and the state of caches at that moment.
Preserve the original query, parameters, node estimates and execution data
before changing resources. If the new plan appears faster, confirm that it
remains faster across the relevant paths and under workload.

A sequential scan can be an efficient choice when a query needs most of a table.
An index can also make a point lookup much faster when it filters to a small
number of blocks. Diagnose the work and selectivity instead of assigning a fixed
judgement to an operation name. Look for the first bad estimate or avoidable
work, then test whether your change improves the end-to-end request and fits the
rest of the workload.

## Further reading

- [PostgreSQL on using EXPLAIN](https://www.postgresql.org/docs/18/using-explain.html)
  explains costs, plan nodes and actual execution reporting.
- [PostgreSQL planner statistics](https://www.postgresql.org/docs/18/planner-stats.html)
  describes what the planner knows about row distributions.
- [PostgreSQL EXPLAIN reference](https://www.postgresql.org/docs/18/sql-explain.html)
  documents measurement options and which statements are executed.

<https://engineer.company/glossary/query-plan/>
