If you’ve ever run a query and stared at the loading spinner thinking “why is this taking so long?”, it’s time to stop guessing.
Almost every time a query is slow, it’s not the fault of PostgreSQL. It’s that we don’t know what it is doing under the hood.
And that’s where EXPLAIN ANALYZE shines.
It’s the closest thing to popping the hood of your car while the engine is running: you see exactly what is happening, how long each part takes, and where everything is getting clogged.
What Exactly Does EXPLAIN ANALYZE Do?
EXPLAIN ANALYZE SELECT ...
It’s two commands in one:
EXPLAIN–> shows you the estimated plan generated by the optimizer (the planner). It’s the theoretical bet on what the cheapest way to execute your query will be.ANALYZE–> actually runs the query and adds real-world runtime metrics:- time taken by each step
- how many rows were actually processed
- how many times each node was executed (loops)
In short:
EXPLAIN = theoryANALYZE = reality
And when it comes to performance… reality always wins.
Important Warning (Don’t Skip This)
EXPLAIN ANALYZE DELETE FROM usuarios WHERE ...
This actually deletes data! The same applies to UPDATE, INSERT … SELECT, etc.
The safe way to test write queries is:
BEGIN;
EXPLAIN ANALYZE DELETE FROM usuarios WHERE email ILIKE '%@prueba.com';
ROLLBACK;
Always run them inside a transaction that you can roll back. It’s a habit that will save you from major disasters.
How to Read the Execution Plan Without Losing Your Mind
The execution plan is an inverted tree (you read it from bottom to top).
- Bottom nodes produce rows
- Top nodes consume / filter / sort / aggregate them
- The topmost node (the root) shows the actual total time for the entire query
Think of it like an assembly line: if a machine at the bottom is slow, the entire process suffers.
The Metrics That Really Matter (Check Them in This Order)
1. Actual Time –> The Source of Truth
It looks like this:
Actual Time=0.015..45.872
- First number: time until the node begins returning the first row
- Second number: total time until it finishes returning all rows
The second value of the root node is the actual total time your query took.
If an intermediate node has a very high actual time –> that’s almost certainly where your problem is.
2. Estimated Rows vs. Actual Rows (Rows vs actual rows)
A classic red flag:
Rows=10000 (estimated)
Actual rows=12
The planner expected 10,000 rows… and only 12 came out. When estimates are off by this much, the execution plan chosen is usually terrible.
Common causes:
- Outdated statistics –> run
ANALYZE table; - Highly skewed data (90% of values are “active”, but you are filtering for “inactive”)
- Column correlations that the planner cannot see
- Functions in the
WHEREclause preventing accurate estimates
Often, a simple ANALYZE fixes the issue. Other times you need partial indexes, extended statistics, or to rewrite the JOIN.
3. Buffers – Always Use EXPLAIN (ANALYZE, BUFFERS)
It tells you whether your bottleneck is I/O or CPU:
shared hit–> the page was already in memory (fast)shared read–> had to read from disk (slow)temp read/write–> spilled to disk (large sorts or hash joins)
Typical patterns:
- High
shared readcount –> I/O issue –> likely a missing index or the working set doesn’t fit in memory - Mostly
hitand still slow –> CPU bound, poor join strategy, or expensive functions executed per row
4. Loops – The Silent Multiplier
Actual rows=1 Loops=45000
This means that node ran 45,000 times. It’s almost always a symptom of a poor Nested Loop choice (the outer side produces many rows, and the inner side lacks a fast index).
The Usual Suspects
Seq Scan
Reads the entire table sequentially. It’s not inherently bad. It’s the best choice if:
- You need to read a large portion of the table
- The table is small
- An index lookup would be more expensive than scanning everything
It becomes suspicious when:
- You expect only a few rows
- The table has millions of records
- There is a highly selective filter without an index –> almost always a mistake
Index Scan vs Bitmap Index Scan
- Index Scan –> perfect for fetching a few rows. Goes straight to the point.
- Bitmap Index Scan –> better when you expect many scattered rows. It builds an in-memory bitmap and then reads full blocks –> fewer random disk seeks.
The planner decides between them based on how many rows it expects to return.
Nested Loop
Very common in small JOINs.
Works great when:
- The left side (outer) returns few rows
- There is an efficient index on the right side (inner)
Turns into a nightmare when:
- The outer side returns thousands or millions of rows
- There is no index on the inner table –> turning into thousands of sequential scans
- Extremely high loop counts
A Real-World Example (The Painful Kind)
Before – Slow query
Seq Scan on transacciones
(actual time=10.542..120.181 rows=50 loops=1)
Filter: (monto > 5000)
Rows Removed by Filter: 999950
What happened:
- Read ~1 million rows
- Discarded 999,950
- Only 50 were useful
- Massive amount of useless I/O
After – With an index on the amount column
Index Scan using idx_transacciones_monto on transacciones
(actual time=0.048..0.117 rows=50 loops=1)
Result: from ~120 ms down to 0.12 ms.
From searching for a needle in a haystack –> to going straight to the needle.
The Bottom Line
EXPLAIN ANALYZE doesn’t guess, doesn’t speculate, and doesn’t sell you snake oil: it shows you what actually happened.
When a query runs slow, the answer is almost always hidden in one (or more) of these:
- A wide gap between estimated and actual rows
- Nodes with very high
actual timein the middle of the tree - High numbers of
shared readortemp write - Abnormally high loop counts
Before rushing to create indexes “just in case”, inspect the plan.
Often, the root issue isn’t a missing index, but rather:
- Outdated statistics
- Inefficient join order
- Broken cardinality estimates
- Functions on columns that prevent index usage
- Filter predicates written in ways that confuse the planner
Optimizing blindfolded is like rolling dice. Optimizing with EXPLAIN ANALYZE is real engineering.
What was the last slow query you had to tackle? Have you run EXPLAIN (ANALYZE, BUFFERS) on it yet?
Try it today on that query you’ve been meaning to speed up… you might be surprised by what you find. Keep coding.