PostgreSQL EXPLAIN ANALYZE: A Guide to Reading Query Plans
Read PostgreSQL EXPLAIN ANALYZE plans using estimates, actual rows, loops and buffers. Try a disposable SQL fixture and identify where estimates diverge.
EXPLAIN ANALYZE runs the statement and prints each plan node's estimated rows beside actual rows and loops, so you can see where the planner's model diverges from execution. Its limits matter: it executes the statement, its timings exclude network transmission and serialization, and profiling overhead can inflate runtime. Your job is to separate an estimate error from genuinely expensive execution — and to run every test on a disposable local database, never production.
By jackey.ye. Updated 2026-12-01.
What Does EXPLAIN ANALYZE Actually Tell You?
It executes the statement and annotates the plan with per-node actual time, actual rows and loops, plus planning and execution time. Plain EXPLAIN only shows the planner's estimates; adding the ANALYZE option causes the statement to actually run and adds the measured statistics, which is how you check whether the estimates are close to reality (EXPLAIN reference).
Each node line carries two halves you must read separately:
Seq Scan on customers c (cost=0.00..189.00 rows=1000 width=15) (actual time=0.015..1.204 rows=1000.00 loops=1)
The cost=…rows=…width=… half is the estimate: startup and total cost, estimated rows, and estimated average row width. The (actual time=… rows=… loops=…) half is the measurement. Cost is expressed in arbitrary units while actual time is milliseconds of real time, so the two are not comparable — the Using EXPLAIN guide says the thing usually most important to look for is whether estimated row counts are reasonably close to reality.
One definition drives most misreading: rows is not the number of rows processed or scanned by the node, but the number emitted by it. A Seq Scan with a Filter can read 10,000 rows and emit 1,000, and the plan reports 1,000. The same page notes that the top-level rows estimate should approximate the rows actually returned, updated or deleted by the query.
How Do You Tell a Bad Row Estimate From Genuinely Expensive Execution?
Compare estimated rows to actual rows per loop at each node. A large ratio means the planner chose a plan on a wrong model of the data; a close estimate paired with high actual time means the work itself is heavy and the plan shape is probably fine.
The arithmetic is per loop, not per node total. If a node reports rows=2 estimated, rows=40.00 actual and loops=100, the planner expected 2 rows per execution and got 40 — a 20× underestimate — while the node emitted 4,000 rows across all executions. Direction matters for join choice. An underestimate makes a nested loop look cheap because the planner prices the inner scan for far fewer outer rows than actually arrive; an overestimate can push the planner toward a hash or merge join, or a sequential scan, that the real data volume did not justify.
Signal in the plan | What it points to | Likely cause | First action |
|---|---|---|---|
Estimated | Bad row estimate (underestimate) | Stale or insufficient statistics; correlated columns treated as independent | Refresh statistics, then consider a higher statistics target or extended statistics |
Estimated | Bad row estimate (overestimate) | Statistics not matching the predicate; expression or type mismatch defeating selectivity | Check the predicate and column statistics before changing planner settings |
Estimate close to actual, but node time dominates | Genuinely expensive execution | Large scan or sort volume, repeated inner scans, spills | Reduce rows earlier, add a supporting index, or restructure the join |
High | Repeated execution of a cheap node | Nested loop driven by a large outer input | Multiply per-loop time by loops to see total cost before optimizing the node |
A useful sanity check on the estimate side: the planner multiplies single-column selectivities when a WHERE clause has several conditions, assuming independence. The row estimation examples show unique1 < 1000 AND stringu1 = 'xxx' estimated at 1 row from 0.100697 × 0.0014559 × 10,000 — arithmetic that collapses the moment the columns are correlated.
How Do You Read Actual Rows and Loops Without Double-Counting Work?
Actual time and rows are per-execution averages, so multiply by loops to get the total time and total rows for that node. The documentation is explicit: the loops value reports the total number of executions of the node, the actual time and rows shown are averages per execution, and you multiply by loops to get total time spent in the node and total rows processed across all executions (Using EXPLAIN).
Documented example, not a benchmark. Values come from the PostgreSQL 19 manual's nested-loop sample plan (tenk2 inner index scan, 10 outer rows). Because actual time and actual rows are printed as per-execution averages, multiply by loops before ranking nodes: 0.003 ms × 10 = 0.030 ms.
Loops exceed 1 for two reasons. First, the inner side of a nested loop runs once per outer row — the docs' example shows an inner index scan executed once per outer row, spending a total of 0.030 milliseconds across 10 rows. Second, parallel execution causes nodes to be executed more than once, and that is also reported through loops.
So a node reporting actual time=0.003..0.003 rows=1.00 loops=10000 looks free per loop and accounts for roughly 30 milliseconds of total node time. Multiply before you rank nodes by cost. The same multiplication explains an actual row count that exceeds the table's physical row count: it is repeated emission, not duplicated storage.
Which EXPLAIN Options Should You Turn On First When Triaging?
Start with ANALYZE, add BUFFERS, reach for VERBOSE only when you need output columns, and switch to FORMAT JSON when a tool will parse the plan. That ordered set covers most triage without drowning the output in detail; the EXPLAIN parameter reference lists the complete set and defaults.
ANALYZE— executes the statement and adds actual time, rows and loops. Without it you have estimates only.BUFFERS— reports shared blocks hit, read, dirtied and written, plus local and temp blocks. A hit means a read was avoided because the block was already cached; temp blocks point at sorts, hashes and materializations spilling to disk.ANALYZEimplicitly enablesBUFFERS, so you rarely type it alone.VERBOSE— adds the output column list per node, schema-qualifies table and function names, and labels variables with their range table alias. Useful when two similarly named relations appear in one plan.FORMAT JSON(or XML/YAML) — the machine-readable form. The text format is compact for humans; the docs recommend a machine-readable format when feeding output to a program.
One trade-off worth knowing before you profile a hot loop: TIMING defaults to TRUE, and the overhead of repeatedly reading the system clock can slow a query significantly on some systems. Setting TIMING OFF keeps actual row counts and total statement runtime while dropping per-node timing — the right choice when you only need to confirm row counts.
How Do You Run EXPLAIN ANALYZE on an UPDATE or DELETE Safely?
Wrap the statement in BEGIN; … ROLLBACK; so it executes and reports actuals while its changes are discarded. The prerequisite is a disposable local database — never production — because the statement really runs and side effects such as triggers still fire inside the transaction.
The EXPLAIN reference states the pattern directly for INSERT, UPDATE, DELETE, MERGE, CREATE TABLE AS and EXECUTE:
BEGIN;
EXPLAIN ANALYZE UPDATE orders SET amount = amount + 1 WHERE order_id < 100;
ROLLBACK;
Two details from the docs affect how you read the result. Execution Time includes executor start-up and shut-down plus time to run fired triggers, but excludes parsing, rewriting and planning. Time spent in BEFORE triggers is counted in the related Insert, Update or Delete node, while AFTER trigger time is not — it is shown separately. Deferred constraint triggers are not considered at all, because they run at end of transaction.
Step-by-Step: Build a Fixture and Read Its Plan
Build the fixture on a disposable local database, load deliberately correlated data, then read the join node with the loops arithmetic. The steps below produce a plan you can inspect end to end; the expected output that follows is illustrative only.
Create a scratch database. Run
CREATE DATABASE explain_lab;and connect with\c explain_lab. Do this on a local instance you can drop afterwards.Create two related tables.
customerskeyed bycustomer_idwith aregioncolumn, andorderswith a foreign key back to it. The foreign key gives the planner an index to consider on the inner side of a join.Load rows with a deliberate correlation. Use
generate_seriesso that one region holds a tenth of the customers, and spread 200,000 orders across them. Correlation between the filter column and the join key is what makes estimates interesting.Collect statistics. Run
ANALYZE customers;andANALYZE orders;so the planner has distribution data instead of defaults.Run the profiled join. Use
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)on the grouped join.Read the output with the loops arithmetic. Compare estimated
rowsto actual rows per loop at the join and scan nodes, then multiply byloops.
-- Run only on a disposable local database.
CREATE DATABASE explain_lab;
\c explain_lab
CREATE TABLE customers (
customer_id integer PRIMARY KEY,
region text NOT NULL
);
CREATE TABLE orders (
order_id bigint PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers(customer_id),
amount numeric(10,2) NOT NULL
);
INSERT INTO customers
SELECT i, CASE WHEN i % 10 = 0 THEN 'APAC' ELSE 'AMER' END
FROM generate_series(1, 10000) AS s(i);
INSERT INTO orders
SELECT i, (i % 10000) + 1, (i % 500)::numeric
FROM generate_series(1, 200000) AS s(i);
ANALYZE customers;
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT c.region, count(*), sum(o.amount)
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE c.region = 'APAC'
GROUP BY c.region;
-- UNEXECUTED EXPECTED OUTPUT (illustrative shape only; not a measured result).
-- Your node types, costs, times and row counts will differ by version, data and hardware.
GroupAggregate (cost=... rows=... width=...) (actual time=... rows=... loops=1)
Group Key: c.region
-> Nested Loop (cost=... rows=... width=...) (actual time=... rows=... loops=1)
-> Seq Scan on customers c (cost=... rows=... width=...) (actual time=... rows=... loops=1)
Filter: (region = 'APAC'::text)
-> Index Scan using orders_pkey on orders o (cost=... rows=... width=...) (actual time=... rows=... loops=<outer rows>)
Index Cond: (customer_id = c.customer_id)
Planning Time: ... ms
Execution Time: ... ms
Checkpoint before you optimize anything: confirm the estimate-versus-actual divergence at the join node. If the inner Index Scan shows loops equal to the number of APAC customers and its actual rows per loop differ sharply from the estimate, you have an estimate problem to chase in the next section. If the estimate is close and the node time dominates, you have a work problem instead.
Reusable checklist for any plan:
Read the plan bottom-up; leaf nodes feed their parents.
Compare estimated
rowsto actual rows per loop at every node, not just the top.Multiply per-loop time and rows by
loopsbefore ranking nodes.Check
Buffersfor read versus hit blocks and for temp blocks that signal spills.Confirm the plan shape matches the data volume before touching planner settings.
What Should You Do After You Find a Large Estimate Error?
Work from least invasive to most: refresh statistics, then raise the statistics target, then add extended statistics for correlated columns. Planner cost parameters are a temporary lever, not a fix — the query planning configuration page calls forcing a different plan with these parameters a temporary solution and points to ANALYZE, default_statistics_target and ALTER TABLE SET STATISTICS as the better ways.
Run
ANALYZEon the table. The EXPLAIN reference notes thatpg_statisticshould be up to date, that autovacuum normally handles it, and that a table with recent substantial changes may need a manualANALYZErather than waiting.Raise the column statistics target. The planner statistics page states the default limit is presently 100 entries for
most_common_valsandhistogram_bounds, settable per column withALTER TABLE … ALTER COLUMN … SET STATISTICSor globally viadefault_statistics_target. Raising it can improve estimates for irregular distributions at the cost of more space inpg_statisticand slightly more estimation time.Add extended statistics for correlated columns. The same page explains that the planner normally assumes multiple conditions are independent, which fails when column values are correlated, and that regular per-column statistics cannot capture cross-column correlation.
CREATE STATISTICSsupports thendistinct,dependenciesandmcvkinds (CREATE STATISTICS).
-- Functional dependency between two correlated columns.
CREATE STATISTICS orders_customer_region (dependencies)
ON customer_id, region FROM customers;
ANALYZE customers;
Two documented limits keep expectations honest. Extended statistics are not currently used by the planner for selectivity estimates made for table joins, and functional dependencies apply only to simple equality conditions comparing columns to constants and IN clauses with constants — not to column-to-column comparisons, range clauses or LIKE.
Can You Trust EXPLAIN ANALYZE Timings as Production Latency?
No. Treat the numbers as relative signals for comparing nodes, not as a latency benchmark for the query in production.
The Using EXPLAIN caveats list two significant ways measured runtimes deviate from normal execution. First, no output rows are delivered to the client, so network transmission costs are not included, and I/O conversion costs are excluded unless SERIALIZE is specified. Second, the measurement overhead added by EXPLAIN ANALYZE can be significant, especially on machines with slow gettimeofday() operating-system calls; the docs point to pg_test_timing to measure that overhead on your system.
Two plan shapes produce misleading row counts. A LIMIT stops a node before it reads all available rows, so the node's actual row count reflects only what the executor pulled. Merge joins have a related artifact: the inner child is backed up and rescanned for duplicate outer keys, and EXPLAIN ANALYZE counts those repeated emissions of the same inner rows as if they were real additional rows — with many outer duplicates, the reported actual row count for the inner child can be significantly larger than the number of rows actually in the relation.
Finally, do not extrapolate. The docs warn that results on a toy-sized table cannot be assumed to apply to large tables, because the planner's cost estimates are not linear and it may choose a different plan at a different size.
FAQ
Does EXPLAIN ANALYZE change my data? It executes the statement, so a data-modifying statement takes effect unless you wrap it in a transaction you roll back. Run it on a disposable database or inside BEGIN; … ROLLBACK;.
Why is actual rows larger than the table's row count? Because of loops and rescans. Actual rows are per-execution averages; multiply by loops for the total, and note that merge joins can count repeated inner rows.
Do I need ANALYZE to get actual numbers? Yes. Plain EXPLAIN shows only estimates; the ANALYZE option executes the statement and adds actual time, rows and loops.
Is a high cost number the same as slow execution? No. Cost is in arbitrary units; actual time is in milliseconds. Compare estimated rows to actual rows, and use actual time for relative node comparison.
Should I change planner settings to force a better plan? Treat that as temporary. The documented better path is refreshing statistics, raising the statistics target, or adding extended statistics for correlated columns.
Where This Fits in a Data Platform
Reading plans is a per-query skill; keeping plans healthy across a platform is an operational one. The same estimate-versus-actual discipline applies when analytical workloads move onto a lakehouse engine, where statistics freshness and join strategy still decide whether a query is fast. If your team is evaluating that move, Singdata's lakehouse overview and its performance report methodology describe how the platform is configured and measured, so you can reproduce the comparison in your own environment rather than relying on headline numbers. For teams standardizing query diagnostics, the Lakehouse Studio workspace is where those SQL checks would run alongside scheduling and governance. Related reading on this site: PostgreSQL column privileges for the access side of the same tables, and ambiguous SQL queries for when a query's intent, not its plan, is the problem.
By jackey.ye. Updated 2026-12-01.