Every backend developer hears it sooner or later: "this page is slow."
You open the code, the ORM query looks reasonable, and still the database takes three seconds to answer. The worst thing you can do at this point is guess. You add an index that does nothing, rewrite a query that was never the problem, or pay for a bigger server.
PostgreSQL has a much better tool: EXPLAIN ANALYZE. It shows exactly how the database ran your query, which steps it took, and how long each one took.
EXPLAIN vs EXPLAIN ANALYZE
EXPLAIN shows the plan PostgreSQL would use, based on estimates. It does not run the query.
EXPLAIN ANALYZE actually executes the query and shows real timings and real row counts. That means a slow SELECT will really be slow, and an UPDATE or DELETE will really change data. For writes, wrap it in a transaction:
BEGIN; EXPLAIN (ANALYZE, BUFFERS) UPDATE orders SET status = 'expired' WHERE created_at < now() - interval '90 days'; ROLLBACK; Step 1: Find the query that is actually slow
Don't start by staring at code. Use pg_stat_statements to see which queries cost the most, sorted by total or mean execution time. The slow query log and auto_explain also help. In Django, Debug Toolbar shows the SQL behind each page.
Step 2: Capture it with realistic values
The plan depends on the values. A customer with 10 orders and a customer with 2 million orders can get different plans. Also test on realistic data volumes, because on a tiny development table PostgreSQL will happily scan everything.
In Django, print(qs.explain(analyze=True, buffers=True)) runs it for you.
Step 3: Read the plan
Here's an example, with illustrative numbers:
Limit (actual time=912.340..912.348 rows=20 loops=1) -> Sort (actual time=912.338..912.342 rows=20 loops=1) Sort Key: created_at DESC -> Seq Scan on orders_order (actual time=0.045..905.120 rows=5312 loops=1) Filter: (customer_id = 42) Rows Removed by Filter: 9994688 Execution Time: 912.390 ms Three rules make this readable:
- Read from the innermost node outward. The deepest nodes run first.
- Actual time and rows are per loop. Multiply by
loopsto get the real total. - A node's time includes its children. Find the node that adds the most time on top of them.
Here the Seq Scan takes 905 ms of 912 ms. And the line Rows Removed by Filter: 9994688 says PostgreSQL read 10 million rows to keep about 5,000. That ratio is the classic signature of a missing or unusable index.
Step 4: Compare estimates with reality
For each node, compare the estimated rows with the actual rows. If they differ by 10x or more, the planner was working with bad information.
A common example: PostgreSQL estimates 1 row, picks a nested loop, and then gets 48,000 rows, so the inner node runs 48,000 times. Causes include stale statistics (run ANALYZE), correlated columns (use extended statistics), and skewed data (raise the statistics target).
Step 5: Match the symptom to the fix
- Seq Scan with a huge "Rows Removed by Filter" → add a matching composite index
- Index exists but isn't used → a function on the column, a type mismatch, or the wrong column order
- Sort with
external merge Disk→ the sort spilled pastwork_mem, so add an index that returns rows in order - Hash Join with
Batches > 1→ the hash spilled to disk - Many fast queries per request → that's an N+1 problem in the app, not a database problem
For the example above, a composite index on (customer_id, created_at DESC) turns the plan into a single Index Scan with no Sort node, and the execution time drops from about 912 ms to under 1 ms.
Change one thing at a time, and never tune planner settings globally as a first move.
Step 6: Re-run and compare
Run EXPLAIN (ANALYZE, BUFFERS) again on the same query, compare the whole plan and not just the total time, and test other parameter values, especially the worst-case ones.
The takeaway
Debugging a slow query is not about intuition. It's about reading evidence: find the node that carries the time, check loops, compare estimated rows with actual rows, and use buffers to see the I/O. Then fix the cause, not the symptom.
I wrote the complete step-by-step guide on my blog, with a node-by-node cheat sheet, a worked Django example, a symptom-to-fix table, and an FAQ:
👉 https://blog.reiteachaigean.com/blog/debug-slow-postgresql-queries-explain-analyze
If you want to go further after reading the plan:
- PostgreSQL Composite Indexes with Django
- Django ORM Optimization for Millions of Records
- select_related vs prefetch_related: Practical Examples
What's the worst query plan you've ever had to debug? Tell me in the comments.