
How to Read Postgres EXPLAIN ANALYZE Output
Query plans are a wall of text and for long time we were looking on them like on a Christmas tree, so now we made the data by ourselves, orders with one million rows, customers with hundred thousand, 4 percent of orders pending, Postgres 18 on the laptop, and we asked for twenty newest pending orders together with the email, with EXPLAIN ANALYZE BUFFERS in front.
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.total, u.email
FROM orders o
JOIN users u ON u.id = o.user_id
WHERE o.status = 'pending'
ORDER BY o.created_at DESC
LIMIT 20;
15.4 ms the answer says, ok, and we are reading from bottom up because the most deep line runs first, there is a seq scan, parallel one, with Rows Removed by Filter 320000, but don't believe this number yet, near it is loops=3, so really it is 960,000 rows read and thrown, 40,000 left, all of them sorted only so we can have 20, therefore we made small index on created_at where status is pending and ran same query again, 0.041 ms, buffers from 7489 down to 66, it walks from newest, takes twenty, stops, nothing to sort.
CREATE INDEX CONCURRENTLY orders_pending_recent
ON orders (created_at DESC)
WHERE status = 'pending';
The loops thing we wanted to see more clear and for this we did ugly settings, hash join off, merge join off, memoize off, no parallel, please not on production, and ordered by total. Now the index scan of customers shows actual time 0.001 ms, who will care about it? But it has loops=40000, and when we look that the seq scan below ends at 25 ms and the nested loop above at 55 ms, then half of our query was living inside this 0.001.
Then we made work_mem very small, 64kB, and sorted the whole million, and plan confessed Sort Method external merge Disk 14648kB, memory was not enough and it was writing files, 215 ms.
And the wrong guess, we did a table where zip always goes together with city, and the planner thought 9 rows will come, came 1000, because it thinks two columns don't know each other and multiplies the chances. After CREATE STATISTICS with dependencies and ANALYZE it guessed 997, the speed stayed same on one table, but imagine joins on top of the guess 9.
CREATE STATISTICS orders_city_zip (dependencies)
ON city, postal_code FROM addresses;
ANALYZE addresses;
See also: choosing indexes and safe migrations.