PREP WITH PROOF
Menu
DATABASES & PERFORMANCE / PRACTICAL GUIDE

PostgreSQL EXPLAIN ANALYZE: Read a Query Plan

Read PostgreSQL query plans with rows, loops, buffers, and index evidence. Includes a bounded SQL walkthrough and a practical before-and-after review workflow.

THE QUICK ANSWER

Use EXPLAIN to inspect an estimated plan and EXPLAIN ANALYZE only when executing the statement is appropriate. Compare estimated and actual output rows, account for loops, and inspect buffer work before choosing a change. Test one hypothesis against the same query and verify that results remain correct.

Capture the right evidence before changing the query

A slow request is not automatically a slow database execution. Write down the application operation, parameter values, expected result count, observed duration, and PostgreSQL version. Separate time waiting for a connection from time executing SQL and transferring results. Otherwise, improving a query plan may leave the actual bottleneck untouched.

Begin with plain EXPLAIN when you need an estimated plan without executing the statement. EXPLAIN ANALYZE actually runs it. A read can still consume resources, wait on locks, or call functions with side effects. A write can modify data and fire triggers. Choose an approved environment and representative workload before collecting execution evidence.

This guide targets PostgreSQL 18 documentation. Its SQL walkthrough is designed for a disposable learning session. PostgreSQL was unavailable in our publication runtime, so the SQL has been reviewed against documentation but not executed here. No plan shape, timing, or speedup below is presented as a measured result.

EXPLAIN (COSTS ON)
SELECT order_id, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

-- Executes the SELECT: choose the environment first.
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT order_id, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Source: PostgreSQL 18: EXPLAIN options and execution behavior ↗

Read the tree in two passes

First identify the output requirements at the top: a limit, sort, aggregate, or join. Then follow each branch toward the scans that supply its rows. Ask which filter should reduce the work and whether it is applied early enough. A large input under a small output can suggest wasted work, but some operations legitimately must inspect the entire input.

On the second pass, compare estimated output rows with actual output rows at the same node. Estimates and observed counts describe rows emitted by that node, not necessarily every row examined. A filter can examine many rows before returning a few. Look at filter and index conditions as well as rows removed.

Cost values are planner units, not elapsed milliseconds. Keep cost separate from actual time. Parent-node times include work in children, so adding every displayed node time double-counts work. With repeated execution, node time and row figures are per-loop averages; use loops to understand the scale. Parallel plans need worker-level context rather than a simple sum of all times.

Field or clueUseful questionCommon misreading
Estimated rows vs actual rowsWas the input size predicted reasonably?Both numbers mean rows scanned
loopsHow often was this node executed?A fast inner node can be ignored
Filter / Index CondWhich condition narrows access versus discards output?Every WHERE predicate is an index lookup
Sort / join / scanWhat requirement causes this operation?An operation name proves it is bad
Execution TimeHow long did this instrumented execution take?It equals end-to-end application latency

Source: PostgreSQL 18: Using EXPLAIN ↗

A small inner scan can become the main workload

Consider an illustrative nested-loop inner node that returns an average of three rows per execution and runs 8,000 times. That represents approximately 24,000 rows returned across its executions. If its average completion time is 0.04 milliseconds, multiplication gives roughly 320 milliseconds of accumulated node time. These are invented arithmetic inputs for learning, not captured PostgreSQL output.

This tells you where to investigate, not what to rewrite immediately. Check why the outer side supplies so many rows and whether the inner lookup has an appropriate access path. Also inspect whether the estimate mismatch begins earlier in the tree. Fixing a downstream symptom may leave the underlying cardinality problem intact.

Do not multiply every metric indiscriminately. Buffer counters are not per-loop row averages, and parent totals overlap child work. A node under LIMIT may stop early, so observed output from that execution does not demonstrate how many rows a full run would emit. Record the execution context before comparing two plans.

Source: PostgreSQL 18: Using EXPLAIN ↗

Buffers describe database-block activity, not a disk benchmark

A shared hit means the requested block was already in PostgreSQL shared buffers. A shared read means it was brought into shared buffers; the operating system may still have cached it. Neither counter is a direct measurement of physical storage latency. Repeated accesses can count the same block more than once.

Upper-node buffer figures include child activity. Compare the overall footprint and investigate the branch that generates it, rather than adding overlapping totals. Temporary-block activity can indicate intermediate data being written and read, such as a sort or hash operation spilling beyond its memory budget.

Explicit BUFFERS makes the intended capture clear. TIMING OFF removes per-node timing instrumentation while retaining execution row information and overall statement timing. Use it when row estimates and work volume are the primary questions. If you later enable node timing, remember that instrumentation itself can affect short queries.

Source: PostgreSQL 18: EXPLAIN options and execution behavior ↗

Build a bounded learning fixture in one session

Use an empty disposable database connection for this walkthrough. Temporary tables belong to the current session; keep the connection open for every block. The fixture deliberately uses a distinctive table name and ON_ERROR_STOP so a script stops on an error instead of continuing with partial setup. It inserts 30,000 synthetic rows, not production customer data.

Customer IDs cycle through 0 to 999, giving each customer 30 rows. Created times advance by one minute per ID, and order_id is unique in the generated data. The payload gives rows some additional width. These choices make the exercise reproducible, but their uniform distribution is unlike many real order systems.

Temporary tables require deliberate statistics maintenance; run ANALYZE after loading this fixture. The standalone ANALYZE command collects planner statistics, while the ANALYZE option on EXPLAIN executes a statement and reports observations. The identical word describes two different jobs.

-- psql script; use one disposable session for all lab blocks.
\set ON_ERROR_STOP on
SET statement_timeout = '10s';
CREATE TEMP TABLE pwp_explain_orders (
  order_id integer NOT NULL,
  customer_id integer NOT NULL,
  created_at timestamp NOT NULL,
  payload text NOT NULL
);
INSERT INTO pwp_explain_orders
SELECT g, g % 1000,
       timestamp '2026-01-01 00:00:00' + g * interval '1 minute',
       repeat('x', 100)
FROM generate_series(1, 30000) AS series(g);
ANALYZE pwp_explain_orders;

Source: PostgreSQL 18: CREATE TABLE and temporary tables ↗

Capture a baseline with the exact same predicate

Run the following query before adding an index. Inspect how the plan obtains customer 42’s rows and satisfies the descending order. A sequential scan and a sort are reasonable possibilities for this unindexed fixture, but record your actual output instead of assuming a particular plan.

The separate SELECT makes correctness visible: the expected 20 IDs descend from 29042 to 10042 in steps of 1000. That expectation follows from the fixture formula and ordering, not from an execution we performed. EXPLAIN ANALYZE does not display the query’s result rows as an ordinary SELECT would.

Save the plan with server version, parameters, and whether it was the first or a repeated execution. A later run can benefit from warmed caches. Avoid presenting one cold baseline and one warm candidate as evidence that the entire improvement came from an index.

EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT order_id, created_at
FROM pwp_explain_orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

SELECT order_id, created_at
FROM pwp_explain_orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Source: PostgreSQL 18: Examining index usage ↗

Test one index hypothesis, then verify results

The candidate index places the equality key before the ordering key. Its hypothesis is that PostgreSQL can find one customer’s entries and obtain the requested ordering with less work. It is not a recommendation to add this exact index to every orders table. Run the same capture and SELECT again after creating it.

Compare result rows, access conditions, sort work, estimated-versus-actual rows, and total execution evidence. If the planner still selects another path, investigate its cost tradeoff rather than disabling sequential scans to force an attractive screenshot. A small table or a predicate returning much of the table can favor a scan.

The query also requests order_id, which this index does not cover. Do not promise an index-only scan from these columns. Any production candidate also has storage and write-maintenance costs. Validate against realistic data distribution and the rest of the workload before deploying it.

CREATE INDEX pwp_explain_customer_created_idx
  ON pwp_explain_orders (customer_id, created_at DESC);
ANALYZE pwp_explain_orders;

EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT order_id, created_at
FROM pwp_explain_orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

-- Re-run the baseline SELECT and compare all returned rows.
-- Optional machine-readable capture:
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, FORMAT JSON)
SELECT order_id, created_at
FROM pwp_explain_orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

-- Cleanup: only this session's temporary learning table.
DROP TABLE pg_temp.pwp_explain_orders;

Source: PostgreSQL 18: Examining index usage ↗

When the estimates disagree, investigate their inputs

If actual output is far larger or smaller than estimated, check whether statistics are current and whether the tested parameter is representative. A popular customer and a rare customer can have very different selectivity. The uniform fixture intentionally does not demonstrate that production skew.

Correlated predicates deserve particular attention. Separate column statistics may not capture how values relate across columns; PostgreSQL supports extended statistics for certain estimation problems. Identify the relevant relationship and consult the documented supported cases before creating a statistics object. More statistics are not a universal fix.

Keep result correctness separate from estimation quality. Rewriting an exclusion predicate can change which NULL values survive, even if the new plan looks cheaper. Use the related SQL NOT IN and NULL guide when those semantics are involved, and compare the required result set before comparing performance.

Source: PostgreSQL 18: Planner statistics ↗

A spill is evidence for investigation, not a global memory setting

If a sort or hash operation reports disk or temporary work, check how much data reaches it and whether the query can reduce or order that input differently. A memory adjustment may help, but first establish whether the operation itself is necessary and whether its row estimate is credible.

work_mem is a budget for individual operations, not a single cap for one connection or the entire server. Several operations, concurrent sessions, and parallel workers can multiply memory demand. Hash operations also have a separate multiplier. A global increase based on one slow query can create a different capacity problem.

Use an isolated, approved experiment if configuration is the hypothesis, then assess concurrency before adopting it. Preserve the original settings with the baseline capture. A faster isolated query is incomplete evidence for a busy application.

Source: PostgreSQL 18: Resource consumption and work_mem ↗

Finish with a decision that another engineer can reproduce

A useful review contains the unchanged query or explicit rewrite, representative parameters, the old and new plans, result checks, and relevant settings. State what improved and what remains uncertain. Keep sensitive literals and identifiers out of public plan-sharing tools unless your organization permits disclosure.

For modifying statements, BEGIN and ROLLBACK can prevent transactional data changes from being committed during an EXPLAIN ANALYZE experiment, but they do not undo every possible effect: sequence advances and external side effects need separate consideration. Prefer a disposable fixture for learning instead of treating rollback as permission to run an unfamiliar write in production.

Choose the smallest change supported by the evidence, validate correctness, and compare under realistic conditions. If database execution is already fast while the request remains slow, return to connection waits, network transfer, and application work. Stop tuning the plan when it no longer explains the observed problem.

Source: PostgreSQL 18: EXPLAIN options and execution behavior ↗

KEEP THESE THREE THINGS

Your next steps

  1. Capture the query, parameters, environment, and baseline before proposing an index or configuration change.
  2. Read row estimates, repeated work, and buffer activity together; preserve the query’s result semantics.
  3. Validate the candidate on representative data and include limitations in the review.

Sources & official resources

Linked resources checked on 2026-10-23. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →