SQL course · Module 9: Performance · Lesson 32 of 40
Quick answer: EXPLAIN shows the plan PostgreSQL chooses for a query: a tree of steps (nodes) with estimated costs and row counts. EXPLAIN ANALYZE actually runs the query and adds the real time and real row count for each node, so you can compare the planner’s guesses with reality. Read the plan from the most indented node upward. Because PostgreSQL EXPLAIN ANALYZE really executes the statement, wrap INSERT, UPDATE and DELETE in BEGIN … ROLLBACK.
In this lesson you will learn:
- how to read plan nodes bottom-up and what
cost,rowsandwidthmean - the difference between
EXPLAINandEXPLAIN ANALYZE, and how to use it safely on writes - what
BUFFERSshows and how to spot a bad row estimate - the three join nodes (nested loop, hash, merge) and the sort and aggregate nodes
- how a plan changes before and after you add an index
Before you start: Lesson 31, How SQL Indexes Work: B-tree, Composite, Covering and Partial Indexes.
We ran every example on PostgreSQL 16.15 with the shop database from Lesson 3 and checked the current PostgreSQL 18 manual. Times and the hit/read split of buffers depend on your computer and cache, and costs depend on your settings and statistics. Treat our numbers as examples, not benchmarks.
Table of Contents
Setup: practice tables and fresh statistics
The shop tables are tiny, so we also use the practice tables from Lesson 31. The same script creates them (it is safe to run again):
DROP TABLE IF EXISTS big_orders, big_customers;
CREATE TABLE big_customers (
id integer PRIMARY KEY,
email text NOT NULL,
country text NOT NULL,
signup_date date NOT NULL
);
CREATE TABLE big_orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES big_customers (id),
order_date date NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL
);
SELECT setseed(0.31); -- fixed seed: everyone gets the same "random" data
INSERT INTO big_customers
SELECT i,
CASE WHEN i % 3 = 0 THEN 'Customer' || i || '@Example.com'
ELSE 'customer' || i || '@example.com' END,
(ARRAY['Pakistan','India','UK','USA','Canada','Germany','France','Italy'])[1 + floor(random() * 8)::int],
DATE '2023-01-01' + floor(random() * 1000)::int
FROM generate_series(1, 20000) AS i;
INSERT INTO big_orders
SELECT i,
1 + floor(random() * 20000)::int,
DATE '2024-01-01' + floor(random() * 1035)::int,
CASE WHEN r < 0.80 THEN 'delivered'
WHEN r < 0.90 THEN 'shipped'
WHEN r < 0.95 THEN 'cancelled'
ELSE 'pending' END,
round((5 + random() * 495)::numeric, 2)
FROM (SELECT i, random() AS r FROM generate_series(1, 200000) AS i) AS s;
VACUUM ANALYZE big_customers, big_orders;
The planner chooses plans from statistics, and freshly loaded tables may have none. Refresh them for the two shop tables we use:
ANALYZE customers, orders;
ANALYZE
Your first plan: cost, rows and width
EXPLAIN
SELECT * FROM customers WHERE country = 'Pakistan';
QUERY PLAN
----------------------------------------------------------
Seq Scan on customers (cost=0.00..1.12 rows=4 width=58)
Filter: (country = 'Pakistan'::text)
(2 rows)
One node: a sequential scan of customers with a filter. The numbers in brackets are estimates (PostgreSQL docs: Using EXPLAIN):
- cost=0.00..1.12: start-up cost (before the first row comes out) and total cost (to return all rows). The units are “arbitrary”, conventionally counted in disk page reads. They are not milliseconds.
- rows=4: how many rows the planner expects this node to return. Four of our ten customers live in Pakistan.
- width=58: the expected average row size in bytes.
The planner picks the plan with the lowest estimated cost. For a seq scan the docs give the formula: pages read × seq_page_cost + rows scanned × cpu_tuple_cost, plus cpu_operator_cost per row for each WHERE check. With the default settings, a 1,471-page table of 200,000 rows costs 1,471 × 1.0 + 200,000 × 0.01 + 200,000 × 0.0025 = 3,971, the number you will see below.
A plan is a tree: read it bottom-up
Here is a query with a join (Lesson 12), a GROUP BY (Lesson 10) and an ORDER BY:
EXPLAIN
SELECT c.name, COUNT(*) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
ORDER BY orders DESC;
QUERY PLAN
-------------------------------------------------------------------------------------
Sort (cost=2.90..2.93 rows=10 width=20)
Sort Key: (count(*)) DESC
-> HashAggregate (cost=2.64..2.74 rows=10 width=20)
Group Key: c.name
-> Hash Join (cost=1.23..2.52 rows=22 width=12)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (cost=0.00..1.22 rows=22 width=4)
-> Hash (cost=1.10..1.10 rows=10 width=16)
-> Seq Scan on customers c (cost=0.00..1.10 rows=10 width=16)
(9 rows)
The top line and each -> line is a node, and indentation shows which node feeds which. Start at the most indented lines and move up:
Seq Scan on customersreads 10 customers, andHashbuilds an in-memory hash table from them.Seq Scan on ordersreads 22 orders.Hash Joinlooks up each order’scustomer_idin the hash table and outputs 22 joined rows.HashAggregategroups them by name.Sortorders the groups by count.
“The cost of an upper-level node includes the cost of all its child nodes”, so the top line (2.93) is the estimated cost of the whole query.

How PostgreSQL EXPLAIN ANALYZE differs from EXPLAIN
Plain EXPLAIN only plans. EXPLAIN ANALYZE “causes the statement to be actually executed” and adds what really happened (PostgreSQL docs: EXPLAIN):
EXPLAIN ANALYZE
SELECT c.name, COUNT(*) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
ORDER BY orders DESC;
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------
Sort (cost=2.90..2.93 rows=10 width=20) (actual time=0.042..0.043 rows=9 loops=1)
Sort Key: (count(*)) DESC
Sort Method: quicksort Memory: 25kB
-> HashAggregate (cost=2.64..2.74 rows=10 width=20) (actual time=0.031..0.034 rows=9 loops=1)
Group Key: c.name
Batches: 1 Memory Usage: 24kB
-> Hash Join (cost=1.23..2.52 rows=22 width=12) (actual time=0.017..0.022 rows=22 loops=1)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (cost=0.00..1.22 rows=22 width=4) (actual time=0.002..0.003 rows=22 loops=1)
-> Hash (cost=1.10..1.10 rows=10 width=16) (actual time=0.012..0.012 rows=10 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 9kB
-> Seq Scan on customers c (cost=0.00..1.10 rows=10 width=16) (actual time=0.002..0.004 rows=10 loops=1)
Planning Time: 0.042 ms
Execution Time: 0.055 ms
(14 rows)
Each node now has a second bracket. actual time is in real milliseconds (start-up..total), rows is the real number of rows, and loops is how many times the node ran; when it ran more than once, time and rows are per loop. The planner expected 10 groups and got 9: customer 10 has no orders. Planning Time is the time to build the plan; Execution Time is the time to run it. Your times will be different.
EXPLAIN ANALYZE on writes: use BEGIN and ROLLBACK
The manual warns that with ANALYZE “other side effects of the statement will happen as usual”. An UPDATE really updates. Wrap it in a transaction (Lesson 19) and roll it back:
BEGIN;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
UPDATE big_orders SET status = 'shipped' WHERE id = 1;
ROLLBACK;
SELECT id, status FROM big_orders WHERE id = 1;
BEGIN
QUERY PLAN
------------------------------------------------------------------------------
Update on big_orders (actual rows=0 loops=1)
-> Index Scan using big_orders_pkey on big_orders (actual rows=1 loops=1)
Index Cond: (id = 1)
(3 rows)
ROLLBACK
id | status
----+-----------
1 | delivered
(1 row)
The index scan found one row and the update ran, but ROLLBACK undid it. (Update shows rows=0 because it returns no rows.) COSTS OFF, TIMING OFF and SUMMARY OFF hide numbers that change between runs.
BUFFERS and a before/after with an index
BUFFERS adds how many 8 kB pages each node touched. A hit means the page “was found already in cache”; a read came from the operating system or disk. Our practice table has no index on customer_id yet:
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM big_orders WHERE customer_id = 4242;
QUERY PLAN
----------------------------------------------------------------------------------------------------------
Seq Scan on big_orders (cost=0.00..3971.00 rows=10 width=27) (actual time=0.085..6.065 rows=12 loops=1)
Filter: (customer_id = 4242)
Rows Removed by Filter: 199988
Buffers: shared hit=1471
Planning:
Buffers: shared hit=9
Planning Time: 0.015 ms
Execution Time: 6.069 ms
(8 rows)
Rows Removed by Filter: 199988 is the warning sign: the scan read all 1,471 pages to keep 12 rows. Add the index from Lesson 31 and run it again:
CREATE INDEX big_orders_customer_id_idx ON big_orders (customer_id);
CREATE INDEX
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM big_orders WHERE customer_id = 4242;
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on big_orders (cost=4.37..42.02 rows=10 width=27) (actual time=0.018..0.032 rows=12 loops=1)
Recheck Cond: (customer_id = 4242)
Heap Blocks: exact=12
Buffers: shared hit=12 read=2
-> Bitmap Index Scan on big_orders_customer_id_idx (cost=0.00..4.37 rows=10 width=0) (actual time=0.013..0.013 rows=12 loops=1)
Index Cond: (customer_id = 4242)
Buffers: shared read=2
Planning:
Buffers: shared hit=15 read=1
Planning Time: 0.135 ms
Execution Time: 0.046 ms
(11 rows)
Now the query touches 14 pages: 2 index pages and 12 table pages (Heap Blocks: exact=12). The estimated cost fell from 3,971 to 42.02. On our machine the execution time also fell, from about 6 ms to well under 1 ms, but that comparison is for this table, this data and this machine only. The page counts are the more reliable signal. In PostgreSQL 18, EXPLAIN ANALYZE includes BUFFERS automatically, shows actual rows with two decimals (such as rows=12.00) and reports the number of index lookups (PostgreSQL 18 release notes).
Parallel plans
On a larger query you may see Gather or, as here, Gather Merge (which keeps sorted rows in order). It collects rows from worker processes that each run part of a Parallel Seq Scan:
EXPLAIN (COSTS OFF)
SELECT c.country, SUM(o.total) AS revenue
FROM big_orders o
JOIN big_customers c ON c.id = o.customer_id
GROUP BY c.country;
QUERY PLAN
-----------------------------------------------------------------
Finalize GroupAggregate
Group Key: c.country
-> Gather Merge
Workers Planned: 1
-> Sort
Sort Key: c.country
-> Partial HashAggregate
Group Key: c.country
-> Hash Join
Hash Cond: (o.customer_id = c.id)
-> Parallel Seq Scan on big_orders o
-> Hash
-> Seq Scan on big_customers c
(13 rows)
To keep the next plans short, we turn parallel query off for this session only:
SET max_parallel_workers_per_gather = 0;
SET
Estimated vs actual rows
A big gap between the planner’s rows and the actual rows is a common reason for a bad plan. Here the planner cannot know how many orders fall on a Sunday:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT * FROM big_orders WHERE EXTRACT(DOW FROM order_date) = 0;
QUERY PLAN
---------------------------------------------------------------------------------------------
Seq Scan on big_orders (cost=0.00..4471.00 rows=1000 width=27) (actual rows=28328 loops=1)
Filter: (EXTRACT(dow FROM order_date) = '0'::numeric)
Rows Removed by Filter: 171672
(3 rows)
It guessed 1,000 rows and got 28,328. Statistics describe order_date, not the result of EXTRACT, so the planner uses a default guess. In a larger query, an estimate this wrong can lead to the wrong join type. Lesson 33 shows filters the planner understands.
Join nodes: nested loop, hash and merge
PostgreSQL has three ways to join two inputs. The same two tables give each one, depending on the query:
EXPLAIN (COSTS OFF)
SELECT c.country, SUM(o.total) AS revenue
FROM big_orders o
JOIN big_customers c ON c.id = o.customer_id
GROUP BY c.country;
EXPLAIN (COSTS OFF)
SELECT c.id, c.email, o.id AS order_id, o.total
FROM big_customers c
JOIN big_orders o ON o.customer_id = c.id
WHERE c.id BETWEEN 100 AND 105;
EXPLAIN (COSTS OFF)
SELECT c.id, o.id AS order_id
FROM big_customers c
JOIN big_orders o ON o.customer_id = c.id
ORDER BY c.id;
QUERY PLAN
-----------------------------------------------
HashAggregate
Group Key: c.country
-> Hash Join
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on big_orders o
-> Hash
-> Seq Scan on big_customers c
(7 rows)
QUERY PLAN
--------------------------------------------------------------
Nested Loop
-> Index Scan using big_customers_pkey on big_customers c
Index Cond: ((id >= 100) AND (id <= 105))
-> Bitmap Heap Scan on big_orders o
Recheck Cond: (c.id = customer_id)
-> Bitmap Index Scan on big_orders_customer_id_idx
Index Cond: (customer_id = c.id)
(7 rows)
QUERY PLAN
-------------------------------------------------------------------
Merge Join
Merge Cond: (c.id = o.customer_id)
-> Index Only Scan using big_customers_pkey on big_customers c
-> Index Scan using big_orders_customer_id_idx on big_orders o
(4 rows)
- Hash Join (all rows joined): one input goes into an in-memory hash table, “after which the other table is scanned and the hash table is probed for matches”. Good for large, unsorted inputs.
- Nested Loop (6 customers): the inner child runs “once for each row obtained from the outer child”. Good when the outer side is small and the inner side has an index.
- Merge Join (output sorted by
c.id): “requires its input data to be sorted on the join keys”. Here both indexes already return rows inidorder.
Sort and aggregate nodes
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT * FROM big_orders ORDER BY total DESC LIMIT 5;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT * FROM big_orders ORDER BY total DESC;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT status, COUNT(*) FROM big_orders GROUP BY status;
QUERY PLAN
-----------------------------------------------------------------
Limit (actual rows=5 loops=1)
-> Sort (actual rows=5 loops=1)
Sort Key: total DESC
Sort Method: top-N heapsort Memory: 25kB
-> Seq Scan on big_orders (actual rows=200000 loops=1)
(5 rows)
QUERY PLAN
-----------------------------------------------------------
Sort (actual rows=200000 loops=1)
Sort Key: total DESC
Sort Method: external merge Disk: 7584kB
-> Seq Scan on big_orders (actual rows=200000 loops=1)
(4 rows)
QUERY PLAN
-----------------------------------------------------------
HashAggregate (actual rows=4 loops=1)
Group Key: status
Batches: 1 Memory Usage: 24kB
-> Seq Scan on big_orders (actual rows=200000 loops=1)
(4 rows)
With LIMIT 5, the sort keeps only the top 5 rows in 25 kB of memory (top-N heapsort). Sorting all 200,000 rows did not fit in our work_mem (4 MB, the default), so it used 7,584 kB of temporary disk (external merge). HashAggregate groups rows in a hash table; you also saw GroupAggregate, which groups rows that arrive already sorted.
Try it yourself
Use the practice tables, the index on customer_id and the SET from this lesson.
Exercise 1: Read a plan bottom-up
Show the plan (without costs) for the number of orders per country since 1 October 2026, largest first. List the nodes in the order they run.
Exercise 2: Estimated vs actual rows
Customer 12737 has the most orders. Compare the estimated and actual rows for their orders.
Exercise 3: EXPLAIN ANALYZE an UPDATE safely
Mark all pending orders from 2024 as cancelled, see how many rows the scan found, and leave the data unchanged.
Solutions
Solution 1
EXPLAIN (COSTS OFF)
SELECT c.country, COUNT(*) AS orders
FROM big_customers c
JOIN big_orders o ON o.customer_id = c.id
WHERE o.order_date >= '2026-10-01'
GROUP BY c.country
ORDER BY orders DESC;
QUERY PLAN
----------------------------------------------------------------
Sort
Sort Key: (count(*)) DESC
-> HashAggregate
Group Key: c.country
-> Hash Join
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on big_orders o
Filter: (order_date >= '2026-10-01'::date)
-> Hash
-> Seq Scan on big_customers c
(10 rows)
Bottom-up: scan big_customers and build the hash; scan big_orders with the date filter; hash join; group by country; sort.
Solution 2
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT * FROM big_orders WHERE customer_id = 12737;
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on big_orders (cost=4.37..42.02 rows=10 width=27) (actual rows=26 loops=1)
Recheck Cond: (customer_id = 12737)
Heap Blocks: exact=26
-> Bitmap Index Scan on big_orders_customer_id_idx (cost=0.00..4.37 rows=10 width=0) (actual rows=26 loops=1)
Index Cond: (customer_id = 12737)
(5 rows)
The planner expects about 10 orders for every customer, an average from the statistics; this customer has 26. A small gap like this is harmless.
Solution 3
BEGIN;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
UPDATE big_orders SET status = 'cancelled'
WHERE status = 'pending' AND order_date < '2025-01-01';
ROLLBACK;
SELECT COUNT(*) FROM big_orders WHERE status = 'pending' AND order_date < '2025-01-01';
BEGIN
QUERY PLAN
------------------------------------------------------------------------------------
Update on big_orders (actual rows=0 loops=1)
-> Seq Scan on big_orders (actual rows=3545 loops=1)
Filter: ((order_date < '2025-01-01'::date) AND (status = 'pending'::text))
Rows Removed by Filter: 196455
(4 rows)
ROLLBACK
count
-------
3545
(1 row)
The scan found 3,545 rows to update; after ROLLBACK all 3,545 are still pending.
Finally, drop the practice tables:
DROP TABLE big_orders, big_customers;
DROP TABLE
Common mistakes
- Running EXPLAIN ANALYZE on a write without a transaction. It really changes data. Our test
EXPLAIN ANALYZE DELETE FROM orders WHERE id = 4;was stopped only by the foreign key:update or delete on table "orders" violates foreign key constraint "order_items_order_id_fkey" on table "order_items". UseBEGIN…ROLLBACK. - Reading the plan from the top. The top node finishes last. Start with the most indented nodes.
- Treating cost as milliseconds. Cost is in planner units; only
actual timeis in milliseconds. - Putting options after ANALYZE.
EXPLAIN ANALYZE BUFFERS SELECT ...givessyntax error at or near "BUFFERS". WriteEXPLAIN (ANALYZE, BUFFERS) SELECT .... - Testing on a tiny table. The docs warn that results “on a toy-sized table cannot be assumed to apply to large tables”.
Frequently asked questions
What is the difference between EXPLAIN and EXPLAIN ANALYZE?
EXPLAIN shows the planned steps with estimates and does not run the query. EXPLAIN ANALYZE runs it and adds the actual time, rows and loops for every node, so you can see where the time went and where the estimates were wrong.
What does cost mean in EXPLAIN?
Cost is the planner’s estimate in arbitrary units, conventionally based on reading one page sequentially (seq_page_cost = 1.0). The first number is the start-up cost and the second is the total cost. Compare costs between plans for the same query, not with clock time.
Why are the estimated rows different from the actual rows?
Estimates come from statistics, which are samples collected by ANALYZE. They can be stale after big changes, and plain column statistics say nothing about expressions such as EXTRACT(DOW FROM order_date). Run ANALYZE after large data changes and write filters on plain columns.
Summary
- PostgreSQL EXPLAIN shows the plan tree; read it from the most indented node up.
costis start-up..total in planner units,rowsis the expected row count andwidththe row size in bytes.EXPLAIN ANALYZEruns the query and adds actual time, rows and loops; useBEGIN…ROLLBACKfor writes.BUFFERSshows pages touched;Rows Removed by Filterand big estimate gaps point to problems.- Hash joins suit big unsorted inputs, nested loops suit a small outer side with an index, merge joins suit sorted inputs.
Next lesson
Next: Lesson 33, SQL Query Optimization: A Practical Checklist.
Sources
- PostgreSQL documentation: Using EXPLAIN
- PostgreSQL documentation: EXPLAIN
- PostgreSQL documentation: Statistics Used by the Planner
- PostgreSQL 18 release notes (EXPLAIN changes)
- PostgreSQL documentation: Resource Consumption (work_mem)





