Reading preferences
Concept

Reading and Measuring Query Plans

Read a plan as an estimate and measure carefully before tuning.

database, postgresql, explain, query plan, performance, measurement

A plan is a tree of choices

EXPLAIN displays the plan PostgreSQL chooses. A node describes an operation such as a sequential scan, index scan, join, or sort. Costs and row counts without ANALYZE are estimates; costs are relative planner units rather than milliseconds.

SQL illustration

After running the fictional books setup in the same disposable session:

EXPLAIN (COSTS OFF)
SELECT id, title FROM books WHERE pages >= 120;

Illustrative plan shape — actual plans vary:

Seq Scan on books
  Filter: (pages >= 120)

In this possible plan, the scan reads rows and the filter keeps matching ones. A different plan may use an index or other nodes. Exact formatting, estimates, and choices depend on statistics, version, settings, and data. COSTS OFF hides estimates in this illustration; it does not make the plan more accurate.

See the reasoning

Read an illustrative plan tree

Follow one possible plan; PostgreSQL may choose a different one. This is prepared; Intuvo does not run SQL.

Start with the scan

One possible plan and its output
  • Sequential scan on books (current focus)
    • Scan filter: pages >= 120
  • Matches (order unspecified): Kite, Tide, Fern

A sequential scan reads table rows in this illustrative plan.

Measure responsibly

EXPLAIN (ANALYZE, BUFFERS) executes the statement and reports observed row counts and timing as well as buffer information. It adds measurement overhead; repeated runs and caching can change results. Executing writes can change data, and even a SELECT can have side effects through functions or locks. Use an authorised disposable environment and understand the query before measuring.

Compare estimated and actual rows, loops, relevant timing, and buffers in context; parent timings include child work, so do not simply add them. Check statistics and data distribution, verify results, and compare representative workloads under similar conditions. A plan by itself does not prove that a particular index or query rewrite will help in production.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What is a planner cost estimate?
2. What does EXPLAIN ANALYZE do?
3. Why might a sequential scan be chosen for a tiny table?
4. How should a tuning change be evaluated?

References and further reading