Reading EXPLAIN and finding bottlenecks
A query got slow — that does not mean the server is to blame. Look at the plan first: it shows where the database gets its rows and how many it reads.
EXPLAIN and EXPLAIN ANALYZE
EXPLAIN SELECT * FROM orders WHERE customer_id = 7;
Shows the plan and the planner's estimates without running the query.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 7;
Runs the query and adds actual rows, per-node timing, and buffer activity.
BUFFERS matters: it shows whether the data came from the cache or from disk
(shared read).
How to read a plan
Read the plan bottom-up: child nodes execute first, then the parent.
Seq Scan— reads the whole table. Fine for a small table or a query that reads most of the rows anyway.Index Scan— looks up the index and then reads the table.Bitmap Heap Scan— first builds a bitmap of matching pages, then reads the table. Often better for medium result sets.Nested Loop— for each row of the outer node, looks for matches in the inner one. Good at small volumes, dangerous at large ones.Hash Join— builds a hash from one table and probes the other. Usually a win for large selections without an index.Sort— sorting. With many rows, checkwork_memand whether the sort spilled to disk.
Key numbers: rows (estimate) vs actual rows, loops, Rows Removed by
Filter, Buffers. A large gap between the estimate and the actual is a signal
that the statistics are stale or the condition is estimated poorly.
Why an index is not used
The most common reason is a non-sargable condition:
WHERE date_trunc('day', created_at) = DATE '2026-11-20'
An index on created_at stores column values, not the result of a function.
Rewrite it as a range:
WHERE created_at >= DATE '2026-11-20'
AND created_at < DATE '2026-11-21'
Other reasons: implicit type casts, LIKE '%text' with a leading wildcard, OR
across different columns, low selectivity, stale statistics (ANALYZE), a
bloated table and bloat.
OFFSET and deep pagination
ORDER BY created_at DESC LIMIT 50 OFFSET 200000
The database reads and discards 200k rows. As data grows, the page gets more expensive. Keyset pagination continues from the last key:
WHERE (created_at, id) < (:last_created_at, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT 50
Page depth no longer affects the cost. It needs a composite index on
(created_at, id).
The order of investigation
- Reproduce the query and capture
EXPLAIN (ANALYZE, BUFFERS). - Find the node with the largest actual time and row count.
- Compare the estimate with the actual, check the statistics.
- Move the function off the column, rewrite the
OR, add the right index. - Re-run the plan and compare buffers and time.
- Lock the result in with a plan test or a production metric.
An index is not free: it slows down inserts and updates and takes up space. So add it for a specific query, not "just in case".