Reading EXPLAIN

Updated · 9 min read
hardPostgreSQL 18sqlexplainexplain-analyzequery-planperformanceinterview

EXPLAIN in SQL shows the plan the database will use to run a query; EXPLAIN ANALYZE runs the query and adds what actually happened. It is the main tool for understanding a slow query: which tables are scanned and how, how they're joined, how many rows each step produces, and how much data it reads. In this lesson, we will learn to read a plan from the inside out, compare estimated and actual rows, use buffers to measure work, and recognize the common node types.

In One Minute

  • EXPLAIN query shows the chosen plan and its estimates, without running it.
  • EXPLAIN ANALYZE query runs it and shows actual rows per step (careful with UPDATE and DELETE: they really happen).
  • Read a plan from the most indented line outward: inner steps feed outer ones.
  • Estimated rows far from actual rows is the classic sign of a bad plan.
  • BUFFERS counts pages read: the most reliable measure of work.

Syntax

SQL
EXPLAIN SELECT ...;
EXPLAIN ANALYZE SELECT ...;
EXPLAIN (ANALYZE, BUFFERS) SELECT ...;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON) SELECT ...;   -- used in this course
OptionAdds or removes
ANALYZERuns the query; adds actual rows and loops
BUFFERSPages read from memory (hit) and disk (read)
COSTS OFFHides cost estimates
TIMING OFF, SUMMARY OFFHide times, which vary from run to run

This course turns timing off: Try it runs PostgreSQL inside your browser, so milliseconds there aren't server milliseconds. Rows and buffers are the same everywhere.

Estimated vs Actual

The examples use the generated big_payments table from How a Query Runs (20,000 rows):

SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
 
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_payments WHERE student_id = 1234;
Output
CREATE TABLE
 
INSERT 0 20000
 
ANALYZE
 
                                        QUERY PLAN
------------------------------------------------------------------------------------------
 Seq Scan on big_payments  (cost=0.00..378.00 rows=4 width=22) (actual rows=4.00 loops=1)
   Filter: (student_id = 1234)
   Rows Removed by Filter: 19996
(3 rows)

Explanation: The node shows both the estimate (rows=4) and the reality (actual rows=4.00). They agree, so the planner understood the data. Rows Removed by Filter: 19996 says the scan read 20,000 rows to return 4: a sign an index would help. When estimates are off by a factor of 10 or more, the planner may have chosen the wrong join method or join order, and running ANALYZE is the first thing to try.

Buffers: Measuring Work

BUFFERS counts the 8 kB pages a query touched: shared hit from memory, read from disk. It's the fairest way to compare two versions of a query:

SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
CREATE INDEX big_payments_student_idx ON big_payments (student_id);
ANALYZE big_payments;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT count(*) FROM big_payments WHERE student_id = 1234;
Output
CREATE TABLE
 
INSERT 0 20000
 
CREATE INDEX
 
ANALYZE
 
                                      QUERY PLAN
--------------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=4 read=2
   ->  Bitmap Heap Scan on big_payments (actual rows=4.00 loops=1)
         Recheck Cond: (student_id = 1234)
         Heap Blocks: exact=4
         Buffers: shared hit=4 read=2
         ->  Bitmap Index Scan on big_payments_student_idx (actual rows=4.00 loops=1)
               Index Cond: (student_id = 1234)
               Index Searches: 1
               Buffers: shared read=2
 Planning:
   Buffers: shared hit=19 read=2
(12 rows)

Explanation: Read from the innermost line out. The Bitmap Index Scan finds the 4 matching entries in the index (2 pages read). The Bitmap Heap Scan fetches those rows from the table (Heap Blocks: exact=4: 4 table pages). The Aggregate counts them. In total, about 6 pages, against 128 for the sequential scan without the index. Planning: Buffers is the work of making the plan itself.

Bitmap Index Scan feeds Bitmap Heap Scan, which feeds Aggregate; 6 pages instead of 128

Common Plan Nodes

NodeMeans
Seq ScanRead the whole table
Index ScanWalk the index, fetching each matching row from the table
Index Only ScanAnswer from the index alone, without visiting the table
Bitmap Index Scan + Bitmap Heap ScanCollect matching row locations, then fetch them page by page
Nested LoopFor each outer row, look up inner rows
Hash JoinBuild a hash table from one side, probe it with the other
Merge JoinWalk two sorted inputs together
Sort, HashAggregate, LimitSort, group, stop early

A join plan, on the Fee Tracker's own tables:

SQL▶ Try it
EXPLAIN (COSTS OFF)
SELECT s.first_name, p.amount_usd
FROM students AS s
JOIN payments AS p ON p.student_id = s.student_id;
Output
                 QUERY PLAN
--------------------------------------------
 Hash Join
   Hash Cond: (p.student_id = s.student_id)
   ->  Seq Scan on payments p
   ->  Hash
         ->  Seq Scan on students s
(5 rows)

Explanation: The inner Seq Scan on students feeds Hash, which builds a hash table of students. The Seq Scan on payments probes it in the Hash Join. With tables this small, scans are the cheapest choice, and indexes wouldn't help.

Scans read data; joins combine inputs; Sort, Aggregate and Limit shape the result

Plans in Other Databases

DatabasePlan onlyWith actual execution
PostgreSQLEXPLAINEXPLAIN (ANALYZE, BUFFERS)
MySQLEXPLAIN (a table of steps)EXPLAIN ANALYZE (8.0.18+)
SQL Server"Estimated execution plan" (SET SHOWPLAN_XML ON)"Actual execution plan" (SET STATISTICS XML ON)
OracleEXPLAIN PLAN FOR ... then DBMS_XPLAN.DISPLAYDBMS_XPLAN.DISPLAY_CURSOR

Tabs showing each database's version are coming to this course.

Read a Plan From the Inside Out

Common Mistakes

Reading a plan top to bottom. The deepest node runs first.

Ignoring estimate errors. Large gaps between rows and actual rows lead to bad plans.

Comparing timings from different runs. Caches change times; compare buffers.

Running EXPLAIN ANALYZE on writes outside a transaction. The changes are real.

Interview Corner

What's the difference between EXPLAIN and EXPLAIN ANALYZE?

EXPLAIN shows the planned execution and estimates without running the query. EXPLAIN ANALYZE runs it and adds actual row counts (and timings), so estimates can be compared with reality.

What does it mean when estimated rows differ greatly from actual rows?

The planner's statistics don't match the data, so it may pick a poor plan. Running ANALYZE, or improving statistics, usually helps.

What's an Index Only Scan?

A scan that answers the query entirely from the index, without reading the table, possible when the index contains every needed column and the visibility map shows the pages are all-visible.

Practice

Challenge: On the generated table without any extra index, show the plan with buffers for counting payments on 2025-06-01. How many rows does the filter remove?

Show solution
SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT count(*) FROM big_payments WHERE paid_on = '2025-06-01';
Output
CREATE TABLE
 
INSERT 0 20000
 
ANALYZE
 
                         QUERY PLAN
------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=128
   ->  Seq Scan on big_payments (actual rows=27.00 loops=1)
         Filter: (paid_on = '2025-06-01'::date)
         Rows Removed by Filter: 19973
         Buffers: shared hit=128
 Planning:
   Buffers: shared hit=22 read=1
(8 rows)

The sequential scan reads all 128 pages and removes 19,973 rows to find 27. Index Design shows how an index on paid_on changes that.

Quick check: Reading EXPLAIN

3 questions
1Which line of a plan runs first?
2A Seq Scan shows Rows Removed by Filter: 19996 and actual rows=4. What does that suggest?
3Why does this course turn timing off in EXPLAIN?

Key Takeaways

You want toUse
See the planEXPLAIN SELECT ...
See what really happenedEXPLAIN (ANALYZE, BUFFERS) SELECT ...
Compare versions steadilyEXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
Analyze a write safelyBEGIN; EXPLAIN ANALYZE UPDATE ...; ROLLBACK;

Was this tutorial helpful?

Lesson 80 of 115