Skip to content

Lesson 17 of 29Indexes and query performance

Reading EXPLAIN and EXPLAIN ANALYZE

Read a Postgres query plan inside-out, spot the estimate that went wrong, and turn a multi-second query into a millisecond one, with runnable SQLite plans.

24 min read0/5 questions

An alert fires: the "recent orders" endpoint went from 40 ms to 3 seconds at p95 after a big customer migrated in. Nobody changed the code. The only tool that tells you what the database is actually doing is the query plan, and reading it is the most valuable database skill a backend engineer can have. Seniors do not guess which index is missing; they read the plan, find the one node where the time goes, and check whether the planner's guess about row counts was wrong. This lesson teaches you to do that with real Postgres plans, and to practice on SQLite plans you can run.

Estimated plans and real ones

EXPLAIN shows the plan the planner would use, with its estimates. It does not run the query, so it is safe and instant.

EXPLAIN ANALYZE runs the query and adds what really happened: time, rows and loops for every node. That means it really executes the statement. EXPLAIN ANALYZE DELETE FROM orders WHERE ... deletes the rows. When you analyse a write, wrap it in a transaction you throw away:

BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders SET status = 'cancelled' WHERE status = 'pending' AND created_at < now() - interval '30 days';
ROLLBACK;

The options you will use:

  • ANALYZE: execute and measure.
  • BUFFERS: how many 8 kB pages each node touched, and whether they came from memory (shared hit) or had to be read (read). Since Postgres 18 it is on by default whenever you use ANALYZE; on older versions, ask for it explicitly. Pages are often a better measure than time, because time changes with what is cached and pages do not.
  • VERBOSE: output columns and schema-qualified names.
  • SETTINGS: any planner settings that differ from the defaults, which explains "it plans differently on my laptop".
  • FORMAT JSON: machine-readable output for visualisers and tooling.

Write it as EXPLAIN (ANALYZE, BUFFERS) SELECT .... The parenthesised form lets you combine options in any order.

Anatomy of a node

Here is the slow "recent orders" query and its plan from Postgres 18. The table has 12 million orders, with an index on created_at but none on customer_id:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, status, created_at
FROM orders
WHERE customer_id = 4217
ORDER BY created_at DESC
LIMIT 20;
Limit  (cost=0.43..1585.31 rows=20 width=24) (actual time=0.081..2741.390 rows=20.00 loops=1)
  Buffers: shared hit=41876 read=139504
  ->  Index Scan Backward using ix_orders_created_at on orders  (cost=0.43..950933.77 rows=12000 width=24) (actual time=0.080..2741.371 rows=20.00 loops=1)
        Filter: (customer_id = 4217)
        Rows Removed by Filter: 11384102
        Index Searches: 1
        Buffers: shared hit=41876 read=139504
Planning:
  Buffers: shared hit=12
Planning Time: 0.214 ms
Execution Time: 2741.452 ms

Every node has two bracketed groups. The first is the estimate:

  • cost=0.43..1585.31: startup cost (before the first row comes out) and total cost (all rows). The units are arbitrary, scaled so that reading one page sequentially costs 1.0. Use them to compare plans for the same query, never as milliseconds.
  • rows=20: how many rows the planner expects this node to output.
  • width=24: the expected average row size in bytes.

The second is what happened:

  • actual time=0.081..2741.390: milliseconds to the first row and to the last row, per loop.
  • rows=20.00: rows output, per loop. Postgres 18 prints two decimals because it is an average across loops.
  • loops=1: how many times the node ran. For the inner side of a nested loop this can be thousands, and then the real total time is roughly actual time × loops.

Under each node come the details that matter most: Filter and Rows Removed by Filter (rows read and thrown away), Index Cond (the part answered by the index itself), and Buffers.

Read this plan and the story is plain. The planner believed customer 4217 had about 12,000 orders spread over time, so walking the created_at index backwards would find 20 of them almost immediately. It costed the Limit at 20/12,000 of the full index scan. In reality the customer has 31 orders, all from 2024, so Postgres walked 11.4 million index entries, discarding them one by one, before it found 20. One wrong estimate, about 400 times too high, turned a smart plan into a disaster.

Note the subtlety: under a Limit, the child node stops early, so its actual rows (20) will not match its estimate (12,000) even when the estimate is right. Here the giveaway is Rows Removed by Filter, not the row count.

The fix is an index that answers both the filter and the order:

CREATE INDEX CONCURRENTLY ix_orders_customer_created ON orders (customer_id, created_at);
Limit  (cost=0.56..76.21 rows=20 width=24) (actual time=0.041..0.067 rows=20.00 loops=1)
  Buffers: shared hit=7 read=3
  ->  Index Scan Backward using ix_orders_customer_created on orders  (cost=0.56..117.82 rows=31 width=24) (actual time=0.040..0.063 rows=20.00 loops=1)
        Index Cond: (customer_id = 4217)
        Index Searches: 1
        Buffers: shared hit=7 read=3
Planning:
  Buffers: shared hit=16 read=1
Planning Time: 0.198 ms
Execution Time: 0.089 ms

The filter became an Index Cond, nothing is removed, and the scan touches 10 pages instead of 181,380. Execution dropped from 2.7 seconds to under 0.1 ms. That comparison of pages is the most convincing thing you can paste into a pull request.

Read the tree inside-out

A plan is a tree. Each -> is a child node, and indentation shows nesting. Data flows upwards: leaves read tables or indexes, and each parent consumes its children's rows. So you read from the most indented node outwards, and among siblings, the first child is usually the "outer" or driving input.

Two rules keep you from misreading times:

  • A parent's time includes its children. A Hash Join with actual time=..6900 whose children took 6,850 ms only spent 50 ms itself. To find the expensive node, subtract.
  • Multiply by loops. A child with actual time=0.061 and loops=53120 cost about 3.2 seconds, not 0.06 ms.

Visualisers do this arithmetic for you. Paste a plan into explain.dalibo.com or explain.depesz.com and they highlight the nodes with the most exclusive time, which is a great habit when a plan has thirty nodes. For the second example, though, read it by hand once:

A plan with a 10,000x misestimate, read inside-out
Nested Loop6,911 ms total, rows=53120Index Scan on ordersest 5 rows, actual 53120Seq Scan on promotions2000 rows, read onceMaterializeloops=53120root

Start at the outer leaf. The planner expected 5 pending orders since yesterday. There were 53,120, because a payment outage left them pending and statistics had not caught up.

1/4

Here is the full text of that plan:

EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.created_at, p.code, p.percent_off
FROM orders o
JOIN promotions p ON p.code = o.promo_code
WHERE o.status = 'pending' AND o.created_at >= '2026-10-21';
Nested Loop  (cost=0.43..153.62 rows=1 width=44) (actual time=0.412..6907.338 rows=53120.00 loops=1)
  Join Filter: (o.promo_code = p.code)
  Rows Removed by Join Filter: 106186880
  Buffers: shared hit=49235 read=3412
  ->  Index Scan using ix_orders_status_created on orders o  (cost=0.43..8.46 rows=5 width=24) (actual time=0.038..71.902 rows=53120.00 loops=1)
        Index Cond: ((status = 'pending'::text) AND (created_at >= '2026-10-21 00:00:00+00'::timestamp with time zone))
        Index Searches: 1
        Buffers: shared hit=49210 read=3412
  ->  Materialize  (cost=0.00..55.00 rows=2000 width=28) (actual time=0.000..0.061 rows=2000.00 loops=53120)
        Buffers: shared hit=25
        ->  Seq Scan on promotions p  (cost=0.00..45.00 rows=2000 width=28) (actual time=0.009..0.190 rows=2000.00 loops=1)
              Buffers: shared hit=25
Planning Time: 0.377 ms
Execution Time: 6911.084 ms

The key diagnostic in any plan is the gap between estimated rows and actual rows on the same node. Within a factor of a few is normal. Ten times or more, especially near the leaves, means the planner was working from bad information, and every decision above that node, such as join method, join order and memory, was made for a query that does not exist. Here the orders scan estimated 5 and got 53,120. The cause was stale statistics on a table that had just received a burst of new rows, as described in Why the database ignored your index. After ANALYZE orders:

Hash Join  (cost=70.00..3261.87 rows=52480 width=44) (actual time=0.512..58.214 rows=53120.00 loops=1)
  Hash Cond: (o.promo_code = p.code)
  Buffers: shared hit=49235 read=3412
  ->  Index Scan using ix_orders_status_created on orders o  (cost=0.43..2904.12 rows=52480 width=24) (actual time=0.031..39.877 rows=53120.00 loops=1)
        Index Cond: ((status = 'pending'::text) AND (created_at >= '2026-10-21 00:00:00+00'::timestamp with time zone))
        Index Searches: 1
        Buffers: shared hit=49210 read=3412
  ->  Hash  (cost=45.00..45.00 rows=2000 width=28) (actual time=0.452..0.453 rows=2000.00 loops=1)
        Buckets: 2048  Batches: 1  Memory Usage: 134kB
        Buffers: shared hit=25
        ->  Seq Scan on promotions p  (cost=0.00..45.00 rows=2000 width=28) (actual time=0.007..0.181 rows=2000.00 loops=1)
              Buffers: shared hit=25
Planning Time: 0.351 ms
Execution Time: 61.005 ms

Same pages read, same rows, a hundred times faster. The estimate is now close (52,480 against 53,120), so the planner builds a hash table of promotions once and probes it per order. No index was added. The data did not change. Only the planner's knowledge did.

Scan nodes

These are the leaves you will meet every day:

  • Seq Scan: read every page of the table in order. Correct for small tables and for queries that return a large share of rows. Suspicious on a big table with a selective filter, especially with a large Rows Removed by Filter.
  • Index Scan: descend the index, then fetch each matching row from the table (the heap). Great for a few rows, and it returns rows in index order, so it can satisfy ORDER BY with no sort.
  • Index Only Scan: answer from the index alone, because it contains every column the query needs. Look at Heap Fetches. Postgres must check the table for any page not marked all-visible in the visibility map, so a high Heap Fetches means VACUUM is behind and you are not getting the benefit. You met covering indexes in Composite, covering and partial indexes.
  • Bitmap Index Scan + Bitmap Heap Scan: a two-step plan for a medium number of rows. First collect all matching row locations from one or more indexes into a bitmap (this is how BitmapAnd and BitmapOr combine indexes), then read the heap pages in physical order. Recheck Cond appears because, when the bitmap gets too big for work_mem, it stores whole pages instead of rows (Heap Blocks: exact=... lossy=...) and each row must be checked again.
Bitmap Heap Scan on orders  (cost=1012.43..48237.12 rows=59210 width=24) (actual time=9.884..61.207 rows=60114.00 loops=1)
  Recheck Cond: (status = 'pending'::text)
  Heap Blocks: exact=21873
  Buffers: shared hit=22420
  ->  Bitmap Index Scan on ix_orders_status  (cost=0.00..997.63 rows=59210 width=0) (actual time=6.411..6.412 rows=60114.00 loops=1)
        Index Cond: (status = 'pending'::text)
        Index Searches: 1
        Buffers: shared hit=547

Joins, sorts and aggregates

Postgres has three join algorithms, and the planner picks one per join based on the row estimates:

  • Nested Loop: for each outer row, look up matches on the inner side. Excellent when the outer side is small and the inner side has an index on the join key. Terrible when the outer side is big and the estimate said it was small, as you just saw.
  • Hash Join: build a hash table from the smaller input (the Hash child), then stream the other input and probe it. Good for large, unsorted inputs and equality joins. The hash table must fit in work_mem; if it does not, Batches goes above 1 and the join spills to temporary files on disk.
  • Merge Join: walk two inputs that are both sorted on the join key, like zipping two sorted lists. Good when both sides come pre-sorted from indexes, or for very large joins.

Above the joins you will see:

  • Sort: check Sort Method. quicksort Memory: 25kB is fine. top-N heapsort means a LIMIT let it keep only the best N rows. external merge Disk: 18432kB means the sort spilled to disk.
  • Limit: stops pulling rows from its child once it has enough, which is why plans with LIMIT can have a huge total cost and still run instantly, or, as in the first example, a small cost and run for seconds.
  • Aggregate, HashAggregate (a hash table keyed by the GROUP BY columns), and GroupAggregate (sorted input, one group at a time). HashAggregate can also spill to disk; Postgres reports Batches and Disk Usage for it.

When a sort or hash spills, the cheap fix is often to raise work_mem for that one session or transaction, SET LOCAL work_mem = '64MB', rather than globally. The setting is per operation, per connection, so a large global value multiplied by hundreds of connections and several sorts per query can exhaust memory. The better fix is often to sort or hash fewer rows.

Plans you can run: SQLite's EXPLAIN QUERY PLAN

SQLite has no EXPLAIN ANALYZE, but EXPLAIN QUERY PLAN shows the same decisions in a compact form. The vocabulary:

  • SCAN t: read the whole table. SCAN t USING COVERING INDEX ix: read the whole index instead, which is smaller, but still everything.
  • SEARCH t USING INDEX ix (col=?): seek with an index, then fetch rows. USING COVERING INDEX: seek and answer from the index alone. USING INTEGER PRIMARY KEY (rowid=?): direct lookup by id.
  • USE TEMP B-TREE FOR ORDER BY (or GROUP BY, DISTINCT): a sort step the indexes could not avoid.
  • Lines at the same depth are nested loops, outermost first. SQLite joins are nested loops; it chooses the order and the indexes.

The helper below prints the plan as a tree and, as a stand-in for actual measurements, counts how many virtual machine instructions the query ran, using set_progress_handler:

Pythonsqlite_plans.py
from shopdb import connectdb = connect() steps = 0def tick(): global steps steps += 1 return 0 # returning 0 means "keep going"db.set_progress_handler(tick, 100) # called every 100 VM instructions def explain(sql, params=()): global steps depth = {0: -1} for node_id, parent, _, detail in db.execute("EXPLAIN QUERY PLAN " + sql, params): depth[node_id] = depth.get(parent, -1) + 1 print(" " * depth[node_id] + "- " + detail) steps = 0 rows = db.execute(sql, params).fetchall() print(f" -> {len(rows)} rows, about {steps * 100} VM instructions\n") explain("SELECT * FROM orders WHERE id = ?", (3,))explain("""SELECT c.name, o.id, o.created_at FROM customers c JOIN orders o ON o.customer_id = c.id WHERE c.city = 'London' ORDER BY o.created_at""")explain("SELECT status, count(*) FROM orders GROUP BY status") db.execute("CREATE INDEX ix_orders_customer ON orders (customer_id)")db.execute("CREATE INDEX ix_orders_status ON orders (status)")explain("SELECT customer_id, count(*) FROM orders GROUP BY customer_id")explain("SELECT status, count(*) FROM orders GROUP BY status")
Output
Press Run (⌘ Enter) to see what happens.

On the course's 10 orders, every plan is fast. What you are learning is the shape. The GROUP BY status query needs a temporary B-tree until ix_orders_status exists, after which it reads the index in order and groups as it goes. With an index on customer_id, grouping by it becomes a covering index scan.

Fix three slow queries

Now practice on tables big enough to matter. The block builds 60,000 events, 20,000 orders and their items, then plans three queries an app might run. Each one scans. Add indexes in the marked spot, run again, and get all three to SEARCH with far fewer instructions.

Pythonfix_three.py
import random, timefrom shopdb import connectdb = connect()random.seed(5) kinds = ["login", "view_product", "view_product", "add_to_cart", "checkout"]db.executescript("""CREATE TABLE big_events (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, kind TEXT NOT NULL, created_at TEXT NOT NULL);CREATE TABLE big_orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL);CREATE TABLE big_items (product_id INTEGER, order_id INTEGER, quantity INTEGER, PRIMARY KEY (product_id, order_id));""")db.executemany("INSERT INTO big_events VALUES (?, ?, ?, ?)", ( (i, random.randint(1, 2000), random.choice(kinds), time.strftime("%Y-%m-%d %H:%M", time.gmtime(1767225600 + i * 300))) for i in range(1, 60_001)))db.executemany("INSERT INTO big_orders VALUES (?, ?)", ((i, random.randint(1, 2000)) for i in range(1, 20_001)))db.executemany("INSERT OR IGNORE INTO big_items VALUES (?, ?, ?)", ((random.randint(1, 500), random.randint(1, 20_000), random.randint(1, 3)) for _ in range(60_000))) # ---- Your fixes go here. Add CREATE INDEX statements and run again. ----db.executescript("""""")# ------------------------------------------------------------------------ steps = 0def tick(): global steps steps += 1 return 0db.set_progress_handler(tick, 100) def explain(label, sql): global steps print(label) depth = {0: -1} for node_id, parent, _, detail in db.execute("EXPLAIN QUERY PLAN " + sql): depth[node_id] = depth.get(parent, -1) + 1 print(" " * depth[node_id] + " - " + detail) steps = 0 db.execute(sql).fetchall() print(f" about {steps * 100:,} VM instructions\n") explain("1. A user's latest activity", "SELECT id, kind, created_at FROM big_events WHERE user_id = 42 ORDER BY created_at DESC LIMIT 20")explain("2. Checkouts since June", "SELECT count(*) FROM big_events WHERE kind = 'checkout' AND created_at >= '2026-06-01'")explain("3. A customer's order totals", """SELECT o.id, sum(i.quantity) FROM big_orders o JOIN big_items i ON i.order_id = o.id WHERE o.customer_id = 42 GROUP BY o.id""")
Output
Press Run (⌘ Enter) to see what happens.
Solution and why each index works
CREATE INDEX ix_events_user_created ON big_events (user_id, created_at);
CREATE INDEX ix_events_kind_created ON big_events (kind, created_at);
CREATE INDEX ix_orders_customer ON big_orders (customer_id);
CREATE INDEX ix_items_order ON big_items (order_id, quantity);
  1. (user_id, created_at) puts each user's events together, already sorted by time. SQLite seeks to user 42, reads backwards, and stops after 20. The USE TEMP B-TREE FOR ORDER BY line disappears. This is the same fix as the first Postgres plan in this lesson.
  2. (kind, created_at) serves the equality first and the range second, and because the query only needs those two columns, it becomes a COVERING INDEX search.
  3. Two problems. Nothing indexes customer_id, so the orders side scans. And the primary key of big_items starts with product_id, so it cannot find items by order_id. A composite key's column order matters. With both indexes, the plan becomes two searches, and adding quantity to the items index makes it covering.

Tools for finding the query to explain

Running EXPLAIN on the right query is half the job. In production, find it with:

  • pg_stat_statements: an extension that aggregates every query shape with its call count, total and mean time, rows and buffers. Sort by total_exec_time to find what costs the most overall, which is often a fast query called millions of times rather than the slowest single query.
  • auto_explain: a module that logs the plan of any statement slower than auto_explain.log_min_duration. With log_analyze on, it logs actual timings too, at some overhead, so many teams enable it with sampling. It captures the plan the application really got, with its real parameters, which matters for the generic-plan problem.
  • Your APM or tracing tool, which links a slow endpoint to the SQL it ran.
SELECT calls,
       round(total_exec_time) AS total_ms,
       round(mean_exec_time, 2) AS mean_ms,
       left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Then reproduce with EXPLAIN (ANALYZE, BUFFERS) using realistic parameter values, ideally on a copy of production data. Plans on a tiny development database tell you very little, because with 50 rows a Seq Scan is always the right answer.

Practice

Quick check
You run EXPLAIN ANALYZE DELETE FROM sessions WHERE expires_at < now(); in production psql to see the plan. What happened?
Need a nudge? A hint rules out a wrong answer.
Quick check
An inner node shows actual time=0.050..0.120 rows=3.00 loops=40000. Roughly how much time did it account for?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

What does this print?

from shopdb import connect
db = connect()
sql = "SELECT id FROM orders WHERE status = 'paid' ORDER BY created_at"
for row in db.execute("EXPLAIN QUERY PLAN " + sql):
  print(row[3])
db.execute("CREATE INDEX ix ON orders (status, created_at)")
for row in db.execute("EXPLAIN QUERY PLAN " + sql):
  print(row[3])
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match each line from a Postgres plan to what it tells you.

Choose an item, then its match on the other side.
Put it in order5 steps

Order the steps for diagnosing a slow endpoint.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
EXPLAIN ANALYZE
Runs the statement for real and reports actual time, rows and loops for every plan node. Writes are executed too.
cost
The planner's estimate in arbitrary units, shown as startup..total. Useful for comparing plans, not as a time.
loops
How many times a node ran. Actual time and rows are per loop, so multiply to get the node's total.
Rows Removed by Filter
Rows a node read and then discarded because they failed a condition the index could not apply.
Heap Fetches
Table visits an Index Only Scan still had to make because pages were not marked all-visible.
Hash Join
A join that builds a hash table on one input and probes it with the other. Spills to disk in batches if it exceeds work_mem.
pg_stat_statements
A Postgres extension that records statistics for every query shape, used to find what costs the most time overall.