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.
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 useANALYZE; 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 msEvery 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 roughlyactual 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 msThe 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 Joinwithactual time=..6900whose children took 6,850 ms only spent 50 ms itself. To find the expensive node, subtract. - Multiply by
loops. A child withactual time=0.061andloops=53120cost 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:
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.
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 msThe 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 msSame 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 BYwith 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 highHeap Fetchesmeans 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
BitmapAndandBitmapOrcombine indexes), then read the heap pages in physical order.Recheck Condappears because, when the bitmap gets too big forwork_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=547Joins, 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
Hashchild), then stream the other input and probe it. Good for large, unsorted inputs and equality joins. The hash table must fit inwork_mem; if it does not,Batchesgoes 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: 25kBis fine.top-N heapsortmeans aLIMITlet it keep only the best N rows.external merge Disk: 18432kBmeans the sort spilled to disk. - Limit: stops pulling rows from its child once it has enough, which is why plans with
LIMITcan 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 BYcolumns), and GroupAggregate (sorted input, one group at a time). HashAggregate can also spill to disk; Postgres reportsBatchesandDisk Usagefor 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(orGROUP 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:
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.
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);(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. TheUSE TEMP B-TREE FOR ORDER BYline disappears. This is the same fix as the first Postgres plan in this lesson.(kind, created_at)serves the equality first and the range second, and because the query only needs those two columns, it becomes aCOVERING INDEXsearch.- Two problems. Nothing indexes
customer_id, so the orders side scans. And the primary key ofbig_itemsstarts withproduct_id, so it cannot find items byorder_id. A composite key's column order matters. With both indexes, the plan becomes two searches, and addingquantityto 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 bytotal_exec_timeto 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 thanauto_explain.log_min_duration. Withlog_analyzeon, 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
EXPLAIN ANALYZE DELETE FROM sessions WHERE expires_at < now(); in production psql to see the plan. What happened?actual time=0.050..0.120 rows=3.00 loops=40000. Roughly how much time did it account for?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])Match each line from a Postgres plan to what it tells you.
Order the steps for diagnosing a slow endpoint.
- Tap the steps below in the right order.
- 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.