Query plans with EXPLAIN

Topic 2 of 2 in Performance14 min readBeginnerFree course

Overview

SQL is declarative: you say what you want and the planner decides how to get it — which indexes to use, which table to read first, which join method to apply. Usually it chooses well. When a query is slow, EXPLAIN shows you the plan it chose, so you can see where the time goes and why. Reading plans is the core skill of SQL performance tuning.

This lesson uses the 200,000-row big_orders table from Indexes, plus a 50,000-row big_customers table built the same way.

Timings depend on the machine, so your numbers will differ. The plans below were produced by PostgreSQL 19; the shape of the plan and the ratios between numbers are what matter.

EXPLAIN and EXPLAIN ANALYZE

  • EXPLAIN query shows the plan without running the query, with the planner’s estimates. Safe on anything, even a huge DELETE.
  • EXPLAIN ANALYZE query runs the query and adds what actually happened: real row counts, real times and, since PostgreSQL 18, buffer usage.

Because EXPLAIN ANALYZE really executes the statement, wrap data-changing statements in a transaction you roll back: BEGIN; EXPLAIN ANALYZE DELETE …; ROLLBACK;.

Reading a simple plan

Reading a query plan with EXPLAIN ANALYZE, for EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42 on an example 100,000-row orders table. Before the index: Seq Scan on orders (cost=0.00..1791.00 rows=10 width=40) (actual time=0.03..9.81 rows=10 loops=1), Filter: (customer_id = 42), Rows Removed by Filter: 99990, Execution Time: 9.85 ms. After CREATE INDEX ON orders (customer_id): Index Scan using orders_customer_id_idx (cost=0.29..44.4 rows=10 width=40) (actual time=0.02..0.04 rows=10 loops=1), Index Cond: (customer_id = 42), Execution Time: 0.06 ms. Node type: Seq Scan, Index Scan, Bitmap Heap Scan, Hash Join, Sort and so on. cost: the planner’s estimate in arbitrary units, startup..total. rows: estimated rows versus actual rows — big gaps mean stale statistics, so run ANALYZE. actual time: real milliseconds, only with ANALYZE, which runs the query. Read plans from the most indented line outwards. EXPLAIN only estimates; EXPLAIN ANALYZE really runs the query.

Here’s the customer lookup from the last lesson, before the index existed:

SQL
EXPLAIN ANALYZE SELECT * FROM big_orders WHERE customer_id = 4242;
Text
                                                 QUERY PLAN                                                 
------------------------------------------------------------------------------------------------------------
 Seq Scan on big_orders  (cost=0.00..4100.00 rows=4 width=30) (actual time=1.488..10.300 rows=4.00 loops=1)
   Filter: (customer_id = 4242)
   Rows Removed by Filter: 199996
   Buffers: shared hit=1600
 Planning:
   Buffers: shared hit=18 read=1
 Planning Time: 0.274 ms
 Execution Time: 10.353 ms
(8 rows)

Piece by piece:

  • Seq Scan on big_orders — the node type: read the whole table.
  • cost=0.00..4100.00 — the planner’s estimate, in arbitrary units: cost before the first row (startup) and for all rows (total). Useful for comparing plans, not as a time.
  • rows=4 — how many rows the planner expected; width=30 — their estimated size in bytes.
  • actual time=1.488..10.300 rows=4.00 loops=1 — what really happened: milliseconds to the first and last row, the real row count, and how many times the node ran.
  • Rows Removed by Filter: 199996 — the tell-tale sign of wasted work: almost every row read was thrown away.
  • Buffers: shared hit=1600 — 1,600 pages of 8 kB were read from PostgreSQL’s memory cache (read= would mean from disk).
  • Execution Time — the total.

After CREATE INDEX … (customer_id):

SQL
EXPLAIN ANALYZE SELECT * FROM big_orders WHERE customer_id = 4242;
Text
                                                              QUERY PLAN                                                              
--------------------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on big_orders  (cost=4.45..19.90 rows=4 width=30) (actual time=0.035..0.042 rows=4.00 loops=1)
   Recheck Cond: (customer_id = 4242)
   Heap Blocks: exact=4
   Buffers: shared hit=4 read=3
   ->  Bitmap Index Scan on big_orders_customer_id_idx  (cost=0.00..4.45 rows=4 width=0) (actual time=0.022..0.023 rows=4.00 loops=1)
         Index Cond: (customer_id = 4242)
         Index Searches: 1
         Buffers: shared read=3
 Planning:
   Buffers: shared hit=17 read=1
 Planning Time: 0.320 ms
 Execution Time: 0.072 ms
(12 rows)

Now there are two nodes. The indented one, marked ->, is a child: the Bitmap Index Scan searches the index and produces the locations of matching rows; its parent, the Bitmap Heap Scan, fetches those rows from the table. Plans are trees — read from the most indented node outwards, because each node feeds its rows up to its parent. Seven pages read instead of 1,600, and 0.07 ms instead of 10.

The node types you’ll meet

Ways to read a table:

Node What it does Good when
Seq Scan reads every row small tables, or most rows needed
Index Scan walks the index, fetching each matching row few rows, or rows needed in index order
Index Only Scan answers from the index alone, without touching the table the index contains every column the query needs
Bitmap Index Scan + Bitmap Heap Scan collects matching row locations, then reads the table pages in order a moderate number of rows

Ways to join two inputs:

Node How it works Good when
Nested Loop for each row of one input, look up matches in the other one side is small and the other has an index
Hash Join build a hash table from the smaller input, then probe it with the larger large inputs, equality joins
Merge Join walk two inputs sorted on the join key in step both inputs already sorted (e.g. by index)

Plus Sort, HashAggregate / GroupAggregate (for GROUP BY), Limit, and Gather when PostgreSQL uses several CPU cores in parallel.

A join plan

Revenue per country since September 2026, joining orders to customers:

SQL
EXPLAIN ANALYZE
SELECT c.country, count(*) AS orders, sum(o.total) AS revenue
FROM big_orders AS o
JOIN big_customers AS c ON c.id = o.customer_id
WHERE o.ordered_at >= '2026-09-01'
GROUP BY c.country
ORDER BY revenue DESC;
Text
                                                                 QUERY PLAN                                                                 
--------------------------------------------------------------------------------------------------------------------------------------------
 Sort  (cost=5505.85..5505.87 rows=7 width=46) (actual time=48.293..48.298 rows=7.00 loops=1)
   Sort Key: (sum(o.total)) DESC
   Sort Method: quicksort  Memory: 25kB
   Buffers: shared hit=1984
   ->  HashAggregate  (cost=5505.66..5505.75 rows=7 width=46) (actual time=48.238..48.246 rows=7.00 loops=1)
         Group Key: c.country
         Batches: 1  Memory Usage: 32kB
         Buffers: shared hit=1984
         ->  Hash Join  (cost=4161.18..5469.02 rows=4885 width=12) (actual time=16.310..40.975 rows=5200.00 loops=1)
               Hash Cond: (c.id = o.customer_id)
               Buffers: shared hit=1984
               ->  Seq Scan on big_customers c  (cost=0.00..884.00 rows=50000 width=10) (actual time=0.012..9.575 rows=50000.00 loops=1)
                     Buffers: shared hit=384
               ->  Hash  (cost=4100.00..4100.00 rows=4894 width=10) (actual time=16.265..16.266 rows=5200.00 loops=1)
                     Buckets: 8192  Batches: 1  Memory Usage: 215kB
                     Buffers: shared hit=1600
                     ->  Seq Scan on big_orders o  (cost=0.00..4100.00 rows=4894 width=10) (actual time=0.128..13.960 rows=5200.00 loops=1)
                           Filter: (ordered_at >= '2026-09-01 00:00:00'::timestamp without time zone)
                           Rows Removed by Filter: 194800
                           Buffers: shared hit=1600
 Planning:
   Buffers: shared hit=43 read=8
 Planning Time: 0.480 ms
 Execution Time: 48.404 ms
(24 rows)

Reading from the inside out: scan big_orders, keeping 5,200 recent orders, and build a hash table from them; scan all of big_customers and probe the hash for each customer (Hash Join); group the joined rows by country (HashAggregate); Sort the seven groups by revenue. Notice the estimates (rows=4894, rows=4885) are close to the actual 5,200 — a sign the planner understands the data well. The time is dominated by scanning the orders, so an index on ordered_at is the obvious next step.

Compare a lookup of one customer’s orders, where both sides are tiny:

SQL
EXPLAIN ANALYZE
SELECT o.id, o.total, c.name
FROM big_orders AS o
JOIN big_customers AS c ON c.id = o.customer_id
WHERE o.customer_id = 4242;
Text
                                                                  QUERY PLAN                                                                  
----------------------------------------------------------------------------------------------------------------------------------------------
 Nested Loop  (cost=4.74..28.25 rows=4 width=23) (actual time=0.053..0.061 rows=4.00 loops=1)
   Buffers: shared hit=9 read=1
   ->  Index Scan using big_customers_pkey on big_customers c  (cost=0.29..8.31 rows=1 width=17) (actual time=0.026..0.026 rows=1.00 loops=1)
         Index Cond: (id = 4242)
         Index Searches: 1
         Buffers: shared hit=2 read=1
   ->  Bitmap Heap Scan on big_orders o  (cost=4.45..19.90 rows=4 width=14) (actual time=0.020..0.024 rows=4.00 loops=1)
         Recheck Cond: (customer_id = 4242)
         Heap Blocks: exact=4
         Buffers: shared hit=7
         ->  Bitmap Index Scan on big_orders_customer_id_idx  (cost=0.00..4.45 rows=4 width=0) (actual time=0.009..0.009 rows=4.00 loops=1)
               Index Cond: (customer_id = 4242)
               Index Searches: 1
               Buffers: shared hit=3
 Planning:
   Buffers: shared hit=3
 Planning Time: 0.222 ms
 Execution Time: 0.088 ms
(18 rows)

A Nested Loop with index lookups on both sides — the right choice for a handful of rows. The planner picked a completely different strategy for a different amount of data; that’s what declarative SQL buys you.

Common problems and fixes

1. A function or cast on an indexed column. With an index on ordered_at, counting one day’s orders by casting to a date can’t use it:

SQL
EXPLAIN ANALYZE SELECT count(*) FROM big_orders WHERE ordered_at::date = '2025-06-01';
Text
                                                      QUERY PLAN                                                      
----------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=4602.50..4602.51 rows=1 width=8) (actual time=15.801..15.803 rows=1.00 loops=1)
   Buffers: shared hit=1600
   ->  Seq Scan on big_orders  (cost=0.00..4600.00 rows=1000 width=0) (actual time=0.059..15.731 rows=200.00 loops=1)
         Filter: ((ordered_at)::date = '2025-06-01'::date)
         Rows Removed by Filter: 199800
         Buffers: shared hit=1600
 Planning:
   Buffers: shared hit=23 read=1
 Planning Time: 0.367 ms
 Execution Time: 15.843 ms
(10 rows)

The index is sorted by ordered_at, not by ordered_at::date, so PostgreSQL has to compute the cast for every row. (On a multi-core server you may see this as a Parallel Seq Scan under a Gather node: the same full scan, split across CPU cores.) Rewrite the condition as a range on the raw column:

SQL
EXPLAIN ANALYZE SELECT count(*) FROM big_orders
WHERE ordered_at >= '2025-06-01' AND ordered_at < '2025-06-02';
Text
                                                                              QUERY PLAN                                                                              
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=578.42..578.43 rows=1 width=8) (actual time=0.360..0.361 rows=1.00 loops=1)
   Buffers: shared hit=200 read=2
   ->  Bitmap Heap Scan on big_orders  (cost=6.39..577.91 rows=204 width=0) (actual time=0.080..0.320 rows=200.00 loops=1)
         Recheck Cond: ((ordered_at >= '2025-06-01 00:00:00'::timestamp without time zone) AND (ordered_at < '2025-06-02 00:00:00'::timestamp without time zone))
         Heap Blocks: exact=200
         Buffers: shared hit=200 read=2
         ->  Bitmap Index Scan on big_orders_ordered_at_idx  (cost=0.00..6.33 rows=204 width=0) (actual time=0.045..0.045 rows=200.00 loops=1)
               Index Cond: ((ordered_at >= '2025-06-01 00:00:00'::timestamp without time zone) AND (ordered_at < '2025-06-02 00:00:00'::timestamp without time zone))
               Index Searches: 1
               Buffers: shared read=2
 Planning Time: 0.211 ms
 Execution Time: 0.395 ms
(12 rows)

Forty times faster, same answer. (The alternative is an expression index on (ordered_at::date).) The same applies to lower(email), extract(year …), col + 1 = 5 and implicit casts.

Notice also the estimate in the slow plan: rows=1000 versus an actual 200. PostgreSQL has no statistics about ordered_at::date, so it fell back to a default guess. Big gaps between estimated and actual rows are the most important thing to look for in a plan, because wrong estimates lead to wrong choices — a nested loop over what turns out to be a million rows, say.

2. Stale statistics. After a large import or delete, the planner’s statistics can be out of date. Autovacuum refreshes them eventually; run ANALYZE tablename to do it immediately, then check the plan again.

3. Missing index on a join or filter column. A Seq Scan with a large Rows Removed by Filter on a big table, or a slow nested loop without an index on the inner side, usually means an index is missing — often on a foreign key.

4. Fetching more than you need. SELECT * defeats index-only scans and moves more data; missing LIMITs and huge OFFSETs make the database produce rows you throw away.

Useful EXPLAIN options

  • EXPLAIN (COSTS OFF) — hide the numbers, to compare plan shapes.
  • EXPLAIN (ANALYZE, BUFFERS OFF) — actual times without buffer details.
  • EXPLAIN (FORMAT JSON) — machine-readable output for visualisers such as explain.dalibo.com, which draw the tree and highlight the expensive nodes.

Here’s the shape-only form, which is also what the exercise uses:

SQL
EXPLAIN (COSTS OFF)
SELECT id, shipping_fee FROM orders WHERE customer_id = 1 ORDER BY ordered_at;
Text
            QUERY PLAN             
-----------------------------------
 Sort
   Sort Key: ordered_at
   ->  Seq Scan on orders
         Filter: (customer_id = 1)
(4 rows)

On the real twelve-row shop tables, a sequential scan plus a sort is the best plan — reading one small page beats walking an index. Don’t be alarmed by Seq Scans on small tables.

Tip: tune with evidence. Measure with EXPLAIN ANALYZE, change one thing (an index, a rewrite, ANALYZE), and measure again. Many “optimisations” made without looking at the plan change nothing — or make things worse.

Exercise

Make the planner use the index

The starter builds a 200,000-row big_orders table with an index on ordered_at. A report counts the orders placed on 1 June 2025 with WHERE ordered_at::date = '2025-06-01', and it's slow. Show its plan with EXPLAIN (COSTS OFF) — you'll see a sequential scan (possibly a Parallel Seq Scan on a multi-core server). Then rewrite the condition as a half-open range on ordered_at (on or after 1 June, before 2 June) and show the new plan with EXPLAIN (COSTS OFF), which should use big_orders_ordered_at_idx. Finally run the rewritten query itself; it returns 200.

SQL
CREATE TABLE big_orders AS
SELECT g AS id,
       (g * 7919) % 50000 + 1 AS customer_id,
       timestamp '2024-01-01' + (g % 1000) * interval '1 day'
                              + (g % 1440) * interval '1 minute' AS ordered_at,
       round((g % 9000) / 100.0 + 5, 2) AS total
FROM generate_series(1, 200000) AS g;
CREATE INDEX big_orders_ordered_at_idx ON big_orders (ordered_at);
ANALYZE big_orders;

EXPLAIN (COSTS OFF)
SELECT count(*) FROM big_orders WHERE ordered_at::date = '2025-06-01';

-- rewrite with a range, explain it, then run it

Summary

  • EXPLAIN shows the plan PostgreSQL chose, with estimated costs and row counts; EXPLAIN ANALYZE also runs the query and reports actual times and rows.
  • A plan is a tree of nodes; read it from the most indented node outwards — each node feeds its parent.
  • Seq Scan reads the whole table; Index Scan, Index Only Scan and Bitmap scans use an index; Nested Loop, Hash Join and Merge Join combine tables.
  • Compare estimated rows with actual rows: big differences point to stale statistics (run ANALYZE) or conditions the planner can't estimate.
  • Wrapping an indexed column in a function or cast (ordered_at::date, lower(email)) stops a plain index being used — rewrite the condition or index the expression.