Reading PostgreSQL EXPLAIN ANALYZE: A Worked Example

When a query is slow, EXPLAIN ANALYZE shows what PostgreSQL actually did to run it: which tables it scanned, how it joined them, how many rows each step produced, and where the time went. Reading that output is the most useful skill for fixing slow queries, because it replaces guessing ("maybe we need an index?") with evidence.
This guide builds a small dataset, runs a typical slow query, reads its plan line by line, fixes it, and compares the result. All plans shown are real output from PostgreSQL 16 on a laptop. Your timings will differ, but the shape of the plans will be the same.
EXPLAIN vs EXPLAIN ANALYZE
EXPLAINshows the plan the optimizer chose, with estimated costs and row counts. The query doesn't run.EXPLAIN ANALYZEruns the query and adds the actual time and row count for every step.- Adding
BUFFERSreports how many 8 kB pages each step read from PostgreSQL's cache (shared hit) or had to fetch from the OS or disk (read).
Because EXPLAIN ANALYZE executes the statement, wrap data-changing statements in a transaction you roll back:
BEGIN;
EXPLAIN (ANALYZE, BUFFERS) UPDATE orders SET status = 'paid' WHERE id = 42;
ROLLBACK;A Test Dataset
100,000 users and 2,000,000 orders spread over two years:
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id bigint NOT NULL REFERENCES users(id),
status text NOT NULL,
total_amount numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO users (email)
SELECT 'user' || g || '@example.com' FROM generate_series(1, 100000) g;
INSERT INTO orders (user_id, status, total_amount, created_at)
SELECT 1 + floor(random() * 100000)::bigint,
(ARRAY['pending','paid','shipped','delivered'])[1 + floor(random() * 4)::int],
round((10 + random() * 990)::numeric, 2),
now() - random() * interval '730 days'
FROM generate_series(1, 2000000);
VACUUM ANALYZE;Two details matter when generating test data. The random user_id is computed directly per row. A subquery like (SELECT id FROM users ORDER BY random() LIMIT 1) looks equivalent, but it doesn't reference the outer row, so PostgreSQL evaluates it once and every order gets the same user. And VACUUM ANALYZE refreshes the planner's statistics after a bulk load. Without fresh statistics, the plans won't reflect the real data.
The Slow Query
An account page shows a customer's 20 most recent orders:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, status, total_amount, created_at
FROM orders
WHERE user_id = 4242
ORDER BY created_at DESC
LIMIT 20;Limit (cost=28619.83..28621.93 rows=18 width=29) (actual time=21.754..22.570 rows=20 loops=1)
Buffers: shared hit=14711 read=2606 written=96
-> Gather Merge (cost=28619.83..28621.93 rows=18 width=29) (actual time=21.753..22.569 rows=20 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Sort (cost=27619.81..27619.83 rows=9 width=29) (actual time=20.255..20.255 rows=7 loops=3)
Sort Key: created_at DESC
Sort Method: quicksort Memory: 25kB
-> Parallel Seq Scan on orders (cost=0.00..27619.67 rows=9 width=29) (actual time=1.772..20.228 rows=7 loops=3)
Filter: (user_id = 4242)
Rows Removed by Filter: 666659
Planning Time: 0.132 ms
Execution Time: 22.586 ms22 ms doesn't sound slow, but this is one user on an otherwise idle laptop with the whole table in memory. The plan shows why it won't stay fast.
Reading the Plan
Read a plan from the most indented line outwards. Each -> is a step (a node) that feeds rows to the node above it.
Parallel Seq Scan on orders reads the entire table. Three processes (the leader plus Workers Launched: 2) split the work, which is why the node shows loops=3.
Filter: (user_id = 4242)andRows Removed by Filter: 666659mean each process read about 666,666 rows and threw almost all of them away. The values are per loop, so the total is about 2,000,000 rows read to return 20. That ratio is the clearest sign of a missing index.actual time=1.772..20.228gives the time to the first row and to the last row, in milliseconds, also per loop.rows=7actual againstrows=9estimated shows the planner's estimate was close. A large gap here (estimated 9, actual 90,000) would point to stale or insufficient statistics. RunANALYZE orders, or raise the column's statistics target.
Sort orders the matching rows by created_at DESC. Sort Method: quicksort Memory: 25kB means the sort fit in work_mem. If you see external merge Disk: ..., the sort spilled to temporary files, which is much slower.
Gather Merge combines the sorted output of the three processes, and Limit stops after 20 rows.
Buffers: shared hit=14711 read=2606: the query touched about 17,300 pages, roughly 135 MB, to return 20 rows. That's the number that will hurt under load: the work grows with the size of the table, not with the size of the result, and many concurrent requests like this compete for I/O and CPU.
The Fix: An Index That Matches the Query
The query filters on user_id and sorts by created_at. A composite index on both columns, in that order, serves both at once:
CREATE INDEX orders_user_id_created_at_idx ON orders (user_id, created_at DESC);On a busy production table, use CREATE INDEX CONCURRENTLY so the build doesn't block writes.
Note that the foreign key on orders.user_id didn't create an index. PostgreSQL automatically indexes primary keys and unique constraints, but not the referencing side of a foreign key. Unindexed foreign keys also make deletes on the parent table slow, because each delete has to scan the child table to check for references.
The Result
Limit (cost=0.43..84.59 rows=20 width=29) (actual time=0.014..0.056 rows=20 loops=1)
Buffers: shared hit=18 read=8
-> Index Scan using orders_user_id_created_at_idx on orders (cost=0.43..88.79 rows=21 width=29) (actual time=0.013..0.054 rows=20 loops=1)
Index Cond: (user_id = 4242)
Planning Time: 0.218 ms
Execution Time: 0.066 ms- The
Sortnode is gone. The index already stores each user's orders newest first, so PostgreSQL reads the first 20 entries and stops. FilterbecameIndex Cond: the index finds the matching rows directly instead of reading and discarding everything else.- Pages touched dropped from about 17,300 to 26, and execution time from 22.6 ms to 0.07 ms. More importantly, the cost now depends on the number of rows returned, so it stays flat as the table grows.
Column order matters. An index on (created_at DESC, user_id) would be far less useful here, because the rows for one user would be scattered throughout it.
Reading Joins and loops
Joins add one more thing to watch: the loops count. This query lists the 50 newest pending orders with each customer's email (it uses an index on (status, created_at DESC)):
Limit (actual time=0.027..0.263 rows=50 loops=1)
-> Nested Loop (actual time=0.027..0.260 rows=50 loops=1)
-> Index Scan using orders_status_created_at_idx on orders o (actual time=0.019..0.105 rows=50 loops=1)
Index Cond: (status = 'pending'::text)
-> Memoize (actual time=0.003..0.003 rows=1 loops=50)
Cache Key: o.user_id
-> Index Scan using users_pkey on users u (actual time=0.003..0.003 rows=1 loops=50)
Index Cond: (id = o.user_id)(Cost estimates removed for readability.)
A Nested Loop runs its inner side once per row from its outer side. Here the inner index lookup on users ran loops=50 times at about 0.003 ms each. The real total for that node is time × loops, about 0.15 ms. This multiplication is the most common misreading of plans: a node showing actual time=0.5 with loops=20000 actually cost 10 seconds. Memoize (PostgreSQL 14+) caches inner results by key, which helps when the same user_id repeats. Here every key was different, so it recorded 50 misses.
Nested loops are ideal when the outer side is small, as here. When both sides are large, PostgreSQL usually switches to a Hash Join (build a hash table from one side, probe it with the other) or a Merge Join (walk two sorted inputs together). If you see a nested loop with a large loops count over an expensive inner node, check the row estimates: the planner probably expected far fewer outer rows.
💡 Tip: For long plans, paste the text output into a visualizer such as explain.dalibo.com or explain.depesz.com. They highlight the slowest nodes, apply the loops multiplication for you, and flag large gaps between estimated and actual rows.
Finding Which Queries to Examine
EXPLAIN ANALYZE explains one query. To find out which queries are worth examining, enable the pg_stat_statements extension and sort by total time:
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 2) AS mean_ms, query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;A 20 ms query called a million times a day usually matters more than a 5-second report that runs once. For queries that are only slow occasionally, the auto_explain module can log the plan of any statement that exceeds a time threshold, so you see the plan from the moment it was slow.
Summary
- Use
EXPLAIN (ANALYZE, BUFFERS)and read the plan from the innermost node outwards. - Look for large
Rows Removed by Filterrelative to rows returned. It means the query reads far more than it needs, usually because of a missing index. - Multiply per-loop numbers by
loopsbefore deciding which node is expensive. - Compare estimated and actual rows. Big gaps point to stale statistics and explain bad join choices.
- Design composite indexes around the whole query: equality filters first, then the sort column, so PostgreSQL can skip the sort as well.
- Index foreign key columns yourself. PostgreSQL doesn't do it for you.
If your table is large because it holds time-series data, see our guide to declarative partitioning.
