Reiteach Aigean Logo
Reiteach Aigeanblog.reiteachaigean.com
Admin
HomeAI UpdatesCodingCloudApps & ToolsTech NewsArticles

How to Debug Slow PostgreSQL Queries with EXPLAIN ANALYZE

Learn how to debug slow PostgreSQL queries with EXPLAIN ANALYZE: read query plans, spot seq scans, bad row estimates, sorts and joins, and fix them step by step

S
Sizan Mahmud
Published on December 1, 2026
How to Debug Slow PostgreSQL Queries with EXPLAIN ANALYZE

Introduction

Every backend developer eventually hears the same sentence: "this page is slow". You open the code, the logic looks fine, the ORM query looks reasonable, and yet the database takes three seconds to answer. Guessing at this point is the most expensive thing you can do. You add an index that does nothing, rewrite a query that was never the problem, or throw a bigger server at it.

PostgreSQL gives you a much better tool: EXPLAIN ANALYZE. It shows exactly how the database executed your query, which steps it took, how long each one took, and where the time went. Once you can read its output, most slow queries stop being mysteries.

This guide walks through the whole debugging process step by step: finding the slow query, capturing it correctly, running EXPLAIN ANALYZE, reading every part of the output, identifying the real bottleneck, applying a fix, and proving the fix worked. It includes worked examples, a node-by-node cheat sheet, and Django-specific tips.

EXPLAIN vs EXPLAIN ANALYZE: A Critical Difference

These two commands look similar but behave very differently.

  • EXPLAIN shows the plan PostgreSQL would use, with estimated costs and row counts. It does not run the query.
  • EXPLAIN ANALYZE actually executes the query, then shows the plan together with the real timings and real row counts.

That second point matters for safety:

  • A slow SELECT will really take that long to run.
  • An UPDATE, DELETE, or INSERT will really change your data. If you want to analyze a write, wrap it in a transaction and roll it back:
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders SET status = 'expired' WHERE created_at < now() - interval '90 days';
ROLLBACK;
  • On a busy production database, run it with care: set a statement_timeout for your session, avoid peak hours, and prefer a read replica or a recent copy of the data when possible.

Estimated plans tell you what PostgreSQL expects. Actual numbers tell you what happened. The most valuable insights come from comparing the two.

Step 1: Find the Query That Is Actually Slow

Do not start by staring at code. Start by finding which queries really cost you time. There are four good sources.

1. pg_stat_statements is the best overall tool. It aggregates statistics for every distinct query. Enable it by adding it to shared_preload_libraries, restarting PostgreSQL, and creating the extension:

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

SELECT calls,
       round(total_exec_time::numeric, 1) AS total_ms,
       round(mean_exec_time::numeric, 2)  AS mean_ms,
       rows,
       left(query, 120)                   AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Sort by total_exec_time to find the queries that cost the most overall, and by mean_exec_time to find the individually slowest ones. A query that takes 5 ms but runs a million times can matter more than one that takes 2 seconds once a day. (These column names are for PostgreSQL 13 and newer.)

2. The slow query log. Set log_min_duration_statement = 500 (milliseconds) to log every query slower than half a second, then read the log.

3. auto_explain. This module logs the execution plan of slow queries automatically, so you can see the plan from the moment it was slow in production:

auto_explain.log_min_duration = '500ms'
auto_explain.log_analyze = on      # adds overhead, use carefully

4. Application tools. In Django, Debug Toolbar shows the SQL and the time for each query on a page, which is how most developers first spot the problem.

Step 2: Capture the Exact Query with Realistic Values

The plan depends on the actual values. WHERE customer_id = 42 and WHERE customer_id = 7 may use different plans if one customer has 10 rows and another has 2 million. Always debug with a real, representative query.

In Django, print the SQL:

qs = Order.objects.filter(customer_id=42).order_by("-created_at")[:20]
print(qs.query)

Be aware that str(qs.query) is meant for reading, and quoting of some values may not be exactly what is sent to the database. For parameterized queries copied from logs ($1, $2), substitute real values, or use PREPARE/EXECUTE with EXPLAIN on the execute statement.

Also test on realistic data. On a development database with 500 rows, PostgreSQL will happily use a sequential scan for everything, because that is genuinely the fastest option on tiny tables. A plan from a small table can mislead you completely.

Step 3: Run EXPLAIN (ANALYZE, BUFFERS)

The command you will use most often:

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders_order
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Useful options:

Option What it adds
ANALYZE Runs the query and reports actual times and row counts
BUFFERS Shows how many memory pages were read from cache or disk
VERBOSE Shows output columns and schema-qualified names
SETTINGS Lists non-default planner settings that affected the plan
WAL Shows write-ahead log activity for write queries
TIMING OFF Skips per-node timing, reducing overhead on very fast nodes
FORMAT JSON Machine-readable output for visualizers

In recent PostgreSQL versions (18 and newer), BUFFERS is included automatically with ANALYZE. On older versions, always add it yourself.

In Django, the same thing is one line:

print(qs.explain(analyze=True, buffers=True, verbose=True))

Remember that this executes the query for real.

Step 4: Learn to Read One Line of the Plan

A plan is a tree of nodes. Each node is one operation, such as scanning a table, sorting rows, or joining two inputs. Here is an example from a slow query on a table with 10 million rows (the numbers are illustrative):

Limit  (cost=185432.10..185432.15 rows=20 width=96) (actual time=912.340..912.348 rows=20 loops=1)
  ->  Sort  (cost=185432.10..185445.60 rows=5400 width=96) (actual time=912.338..912.342 rows=20 loops=1)
        Sort Key: created_at DESC
        Sort Method: top-N heapsort  Memory: 30kB
        ->  Seq Scan on orders_order  (cost=0.00..185273.00 rows=5400 width=96) (actual time=0.045..905.120 rows=5312 loops=1)
              Filter: (customer_id = 42)
              Rows Removed by Filter: 9994688
Planning Time: 0.210 ms
Execution Time: 912.390 ms

Take one line apart:

Seq Scan on orders_order  (cost=0.00..185273.00 rows=5400 width=96) (actual time=0.045..905.120 rows=5312 loops=1)

The first parenthesis is the estimate:

  • cost=0.00..185273.00: the first number is the startup cost (work before returning the first row), the second is the total cost. Costs are in arbitrary planner units, not milliseconds. They are only useful for comparing plans.
  • rows=5400: how many rows PostgreSQL estimated this node would return.
  • width=96: the estimated average row size in bytes.

The second parenthesis is the reality:

  • actual time=0.045..905.120: milliseconds until the first row, and until the last row, per loop.
  • rows=5312: how many rows the node actually returned, per loop.
  • loops=1: how many times this node ran.

Two rules save you from the most common misreading:

  1. Actual time and rows are per loop. If loops=48000 and the time is 0.047, the node really consumed about 48000 × 0.047 ≈ 2,256 ms in total.
  2. A node's time includes its children. The Sort above shows 912 ms, but 905 ms of that is the Seq Scan underneath. To find a node's own cost, subtract its children's time.

At the bottom, Planning Time is how long PostgreSQL spent choosing a plan, and Execution Time is the real runtime. Planning time is usually tiny, but if it is large, look at the number of tables joined, partitions, or the use of very complex views.

Step 5: Read the Tree and Find the Real Bottleneck

Plans are indented trees, and execution flows from the innermost nodes outward. The deepest, most indented nodes run first and feed their results up to their parents.

To find the bottleneck:

  1. Start at the top and note the total execution time.
  2. Walk down and, for each node, compare its time with its children's time.
  3. The node where a large amount of time is added on top of its children is the expensive one. Or the deepest node that accounts for most of the total.
  4. Multiply by loops for nodes inside a nested loop.

In the example above, the Seq Scan takes 905 ms of 912 ms in total. Everything else is noise. The line that matters is:

Rows Removed by Filter: 9994688

PostgreSQL read 10 million rows to keep 5,312 of them. That ratio, millions read versus thousands kept, is the signature of a missing or unusable index.

Step 6: Compare Estimates with Reality

This is the most powerful diagnostic technique. For each node, compare the estimated rows with the actual rows.

  • Estimate close to actual: the planner understood your data and probably chose a sensible plan.
  • Estimate off by 10x or more: the planner was working with bad information, and it may have chosen a poor plan because of it.

A classic example (illustrative numbers):

Nested Loop  (cost=0.85..120.40 rows=1 width=64) (actual time=0.040..2310.000 rows=48000 loops=1)
  ->  Index Scan using customer_pkey on customer  (cost=0.43..8.45 rows=1 width=32) (actual time=0.020..15.000 rows=48000 loops=1)
        Filter: (region = 'south' AND tier = 'gold')
  ->  Index Scan using orders_customer_idx on orders_order  (cost=0.42..8.44 rows=1 width=32) (actual time=0.045..0.047 rows=1 loops=48000)
        Index Cond: (customer_id = customer.id)

PostgreSQL estimated 1 row from the customer filter and chose a nested loop, which is excellent for one row. In reality it got 48,000 rows, so the inner index scan ran 48,000 times. Check the math from Step 4: 0.047 ms × 48,000 loops is about 2,256 ms. A hash join would have been far faster, but the planner could not know that.

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

Common causes of bad estimates, and what to do:

  • Stale statistics. Run ANALYZE table_name; (autovacuum normally does this, but not instantly after a huge data load).
  • Correlated columns. The planner assumes columns are independent. If region and tier are strongly related, it multiplies their selectivities and underestimates. Create extended statistics:
CREATE STATISTICS customer_region_tier (dependencies)
ON region, tier FROM customer;
ANALYZE customer;
  • Skewed data. If a few values are very common, raising the statistics detail for that column can help: ALTER TABLE t ALTER COLUMN c SET STATISTICS 500; ANALYZE t; (the default target is 100).
  • Expressions and functions. The planner has limited knowledge about the result of lower(email) or arithmetic, unless you have an expression index or extended statistics on that expression.

Step 7: Know the Nodes You Will See Most

Scan nodes (how rows are read)

Node Meaning When it is a problem
Seq Scan Reads the whole table Slow when it keeps few rows out of millions, and you have no suitable index
Index Scan Walks an index, then fetches table rows Usually good; slow if it fetches huge numbers of rows randomly
Index Only Scan Answers from the index alone Good; check Heap Fetches, because many fetches mean the table's visibility map is out of date
Bitmap Index Scan + Bitmap Heap Scan Builds a bitmap of matching pages, then reads them in order Normal for medium-sized results or combining several conditions; watch "lossy" blocks if work_mem is small

A Seq Scan is not automatically bad. On small tables, or when a query needs a large share of the table, reading everything sequentially is the fastest plan. It is a problem when it reads millions of rows to keep very few.

Join nodes

Node Best at Warning signs
Nested Loop Few outer rows, indexed inner lookup A huge loops count on the inner node
Hash Join Joining large unsorted sets Batches greater than 1 means the hash table spilled to disk
Merge Join Both inputs already sorted Expensive sorts feeding it

Sorting and aggregation

  • Sort Method: quicksort Memory: ... is healthy.
  • Sort Method: external merge Disk: 128000kB means the sort did not fit in work_mem and spilled to disk. Either add an index that returns rows already ordered, reduce the data sorted, or raise work_mem carefully.
  • top-N heapsort is used with ORDER BY ... LIMIT and is cheap in memory, but if the child node had to read millions of rows first, the problem is upstream.
  • HashAggregate and GroupAggregate handle GROUP BY. Watch for large memory use or disk spills, and consider whether filtering earlier could reduce the rows grouped.

Parallel query

Nodes like Gather and Parallel Seq Scan show that PostgreSQL split the work across workers. Compare Workers Planned with Workers Launched. If fewer workers launched than planned, the system was short of worker slots.

Step 8: Use BUFFERS to See the I/O

Time tells you how long. Buffers tell you why.

Buffers: shared hit=120 read=48210 dirtied=0 written=0
  • shared hit: pages found in PostgreSQL's cache (fast).
  • shared read: pages that had to be read from the operating system or disk (slow).
  • dirtied / written: pages modified or flushed, which appear in write queries.
  • temp read / temp written: pages spilled to temporary files, a sign of sorts or hashes that exceeded work_mem.

A node with a huge read count is I/O-bound. Compare cold and warm runs: the first run may show heavy read because the data was not cached, while the second shows mostly hit and runs faster. When you compare before-and-after results, make sure you compare like with like, for example by running each version several times and looking at the warm timings.

Step 9: Fix the Problem, One Change at a Time

Match the symptom to the fix.

Symptom: Seq Scan with a huge "Rows Removed by Filter". Add an index that matches the filter and sort. For the earlier example, a composite index on (customer_id, created_at DESC):

class Meta:
    indexes = [
        models.Index(fields=["customer", "-created_at"], name="order_cust_created_idx"),
    ]

On a large production table, create it without blocking writes using AddIndexConcurrently in a non-atomic migration.

After the index, the plan becomes:

Limit  (cost=0.56..42.10 rows=20 width=96) (actual time=0.031..0.062 rows=20 loops=1)
  ->  Index Scan using order_cust_created_idx on orders_order  (cost=0.56..11200.00 rows=5400 width=96) (actual time=0.030..0.058 rows=20 loops=1)
        Index Cond: (customer_id = 42)
Planning Time: 0.150 ms
Execution Time: 0.085 ms

From about 912 ms to under 1 ms (illustrative), with no sort node at all, because the index returns rows already in order, and LIMIT 20 stops after 20 entries.

Symptom: the planner ignores your index. Common reasons: a function applied to the column (lower(email), created_at::date) without a matching expression index, a leading wildcard like LIKE '%abc', mismatched data types in a comparison, a partial index whose condition is missing from the query, or a table small enough that a scan is cheaper.

Symptom: estimates far from actual rows. Run ANALYZE, add extended statistics, or raise the statistics target for skewed columns.

Symptom: a nested loop with a huge loops count. Fix the row estimates first. If that is not enough, restructure the query, for example by filtering earlier or using a join the planner estimates better.

Symptom: sort or hash spilling to disk (external merge Disk, Batches: 8, temp written). Reduce the data volume, add an index that provides the order, or raise work_mem for that session or role. Raise it carefully: work_mem applies per sort or hash operation, so many concurrent queries can multiply it.

Symptom: OFFSET pagination gets slower on later pages. Switch to keyset pagination (WHERE id > last_id ORDER BY id LIMIT 50).

Symptom: many fast queries add up to a slow request. The plan of each query looks fine, but there are hundreds of them. This is an application-level N+1 problem. Fix it with select_related() and prefetch_related(), not with indexes.

Symptom: the query returns far more data than the page needs. Select only the columns you need, add LIMIT, or aggregate in the database.

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

Two warnings: change one thing at a time so you know what helped, and do not tune planner settings first. Settings such as enable_seqscan = off are useful in a single test session to see whether an alternative plan is possible, but they are not fixes, and should never be changed globally.

Step 10: Re-Run, Compare, and Protect the Fix

After each change:

  1. Run EXPLAIN (ANALYZE, BUFFERS) again on the same query with the same values.
  2. Compare execution time, the shape of the plan, buffer counts, and the estimated versus actual rows.
  3. Try several different parameter values, including the "worst-case" ones, such as the customer with the most rows. A plan that is fast for one customer can be slow for another.
  4. Run ANALYZE if you changed data volumes or added extended statistics.
  5. Confirm the improvement in real traffic, using pg_stat_statements or your monitoring before and after the deployment.

To stop the problem from coming back, add a query-count test for the endpoint with assertNumQueries, keep slow query logging enabled, and review pg_stat_statements regularly.

Worked Example: A Slow Django Endpoint, Start to Finish

Imagine the endpoint "latest 20 orders for a customer" takes almost a second in production.

  1. Find it. pg_stat_statements shows this query near the top of total_exec_time, with a high mean time.
  2. Capture it. In a Django shell, print(qs.query) gives the SQL, and you substitute a real customer ID, ideally one with many orders.
  3. Run it. qs.explain(analyze=True, buffers=True) shows a Seq Scan on orders_order with Rows Removed by Filter: 9994688, and a top-N heapsort above it.
  4. Diagnose. The scan consumes nearly all the time. There is no index on customer_id that also supports ordering by created_at. (Foreign keys get an index in Django by default, but that index alone cannot also return rows in created_at order, and the planner may still choose a scan when that customer has a lot of rows.)
  5. Fix. Add the composite index (customer_id, created_at DESC) concurrently.
  6. Verify. The new plan shows an Index Scan with an Index Cond on customer_id, no Sort node, and execution time in the sub-millisecond range.
  7. Protect. Keep the query under a test, watch the index's idx_scan count in pg_stat_user_indexes, and move on.

Visualizing Plans

For long plans, a visualizer helps. Paste the output (preferably FORMAT JSON or text) into a tool such as explain.depesz.com or explain.dalibo.com. They highlight the slowest nodes, show per-node exclusive time, and flag misestimates. Before pasting plans into any public tool, check them for sensitive table names, column names, and constants, and use a self-hosted option if the data is confidential.

Common Mistakes to Avoid

  1. Using plain EXPLAIN and trusting the estimates. Use ANALYZE to see what really happened.
  2. Analyzing a write without a transaction. Wrap UPDATE, DELETE, and INSERT in BEGIN ... ROLLBACK.
  3. Debugging on tiny data. Plans on small tables do not predict plans on large ones.
  4. Forgetting loops. Per-loop times hide the real total in nested loops.
  5. Assuming every Seq Scan is bad. Sometimes it is the right plan.
  6. Ignoring estimate mismatches. They explain many mysterious bad plans.
  7. Adding an index without re-checking the plan. Confirm the planner uses it.
  8. Changing several things at once. You cannot tell which change helped.
  9. Comparing a cold run with a warm run. Cache state changes timings dramatically.
  10. Tuning planner settings globally. Fix the query, indexes, or statistics instead.
  11. Fixing the wrong layer. If the problem is hundreds of small queries, no index will fix it.

Quick Reference: Symptom to Cause to Fix

What you see in the plan Likely cause Typical fix
Seq Scan, huge Rows Removed by Filter Missing or unusable index Add a matching (often composite) index
Index exists but is not used Function on column, type mismatch, wrong column order Expression index, fix the types, reorder columns
Estimated rows far from actual Stale or insufficient statistics ANALYZE, extended statistics, higher statistics target
Nested Loop with huge inner loops Underestimated outer row count Fix estimates, restructure the query
Sort Method: external merge Disk Sort exceeds work_mem Index for ordering, fewer rows, raise work_mem carefully
Hash Join with Batches > 1 Hash spilled to disk Reduce rows, raise work_mem carefully
Huge shared read Cold cache or too much data read Narrow the scan, check the working set fits in memory
Index Only Scan with many Heap Fetches Visibility map out of date Vacuum the table
Planning Time is large Many joins or partitions Simplify the query, reduce partitions scanned
Many fast queries per request N+1 in the application select_related, prefetch_related, batching

Related Reading: Fixing the Query Is One Part of a Fast System

EXPLAIN ANALYZE tells you where the time goes. These guides cover the fixes that usually follow:

A Practical Checklist

Work through this whenever a query is slow:

  • Identify the query with pg_stat_statements, the slow log, or auto_explain
  • Capture it with realistic, worst-case parameter values
  • Test on realistic data volumes
  • Run EXPLAIN (ANALYZE, BUFFERS), inside BEGIN ... ROLLBACK for writes
  • Find the node where most of the time goes, remembering that loops multiplies
  • Compare estimated rows with actual rows at each important node
  • Look at Rows Removed by Filter, sort methods, hash batches, and temp buffers
  • Check shared read versus shared hit to separate I/O from CPU
  • Apply one fix at a time: index, rewrite, statistics, or memory
  • Re-run the same query and compare the whole plan, not just the total time
  • Test other parameter values and warm versus cold runs
  • Keep monitoring so a regression is caught early

Conclusion

Debugging a slow PostgreSQL query is much less about intuition and much more about reading evidence. EXPLAIN ANALYZE shows you the exact path the database took, the time each step consumed, and where its expectations differed from reality. Read the plan from the innermost node outward, find the node that carries the time, check loops, compare estimated rows with actual rows, and use buffers to understand the I/O.

Then fix the cause, not the symptom: the right index for a scan that discards millions of rows, fresh or extended statistics for bad estimates, a rewritten query for a bad join order, or application changes when the real problem is too many queries. Re-run the plan to prove the improvement. With this routine, a slow query stops being a mystery and becomes a ten-minute investigation.

Frequently Asked Questions

What does EXPLAIN ANALYZE do in PostgreSQL? It runs the query and prints the execution plan together with real timings and row counts for every node. Plain EXPLAIN only shows the estimated plan without executing the query, so EXPLAIN ANALYZE is the tool for finding out where time is actually spent.

Is it safe to run EXPLAIN ANALYZE on production? It executes the query for real, so a slow query will be slow and a write query will change data. For UPDATE, DELETE, and INSERT, wrap it in BEGIN ... ROLLBACK. On busy systems, set a statement_timeout, avoid peak hours, and consider a replica or a restored copy of the data.

How do I read EXPLAIN ANALYZE output? Read the plan as a tree from the innermost, most indented nodes outward. For each node, compare estimated rows with actual rows, multiply per-loop time by loops, and look for the node that adds the most time on top of its children. The cost numbers are in planner units, not milliseconds.

What does cost mean in a PostgreSQL query plan? It is an arbitrary unit the planner uses to compare candidate plans, with a startup cost and a total cost. It is not time. Use actual time from EXPLAIN ANALYZE for real durations.

Why is PostgreSQL using a Seq Scan instead of my index? Possible reasons: the table is small or the query needs a large share of rows, so scanning is cheaper; a function is applied to the indexed column; the comparison uses mismatched data types; the leading column of a composite index is not in the query; a partial index's condition is missing; or statistics are stale. Check the plan and run ANALYZE.

What are rows estimated versus rows actual? rows in the first parenthesis is the planner's guess, and rows in the actual section is what really happened. A large gap, such as 1 versus 48,000, means bad statistics and often leads to a poor plan. Fix it with ANALYZE, extended statistics, or a higher statistics target.

What does "Rows Removed by Filter" mean? It is the number of rows a node read and then discarded because they did not match the filter. A huge number compared with the rows returned usually means PostgreSQL scanned far more data than needed, which points to a missing or unsuitable index.

What does BUFFERS add to EXPLAIN ANALYZE? It shows how many memory pages were served from cache (shared hit), read from disk or the OS (shared read), modified, or spilled to temporary files. It helps you tell whether a slow node is I/O-bound or CPU-bound. Recent PostgreSQL versions include it automatically with ANALYZE.

How do I run EXPLAIN ANALYZE from Django? Call queryset.explain(analyze=True, buffers=True, verbose=True) and print the result. It executes the query, so use realistic data and be careful on production databases.

Share this article

Pass this technical dispatch along to fellow engineers

Did you enjoy this article?

Rate it so we know what content to bring next

Comments (0)