Reading PostgreSQL Query Plans With EXPLAIN ANALYZE

databaseperformancepostgresqlsql
Reading PostgreSQL Query Plans With EXPLAIN ANALYZE

A slow query lands on your desk. You run EXPLAIN ANALYZE, spot the words "Seq Scan", add an index, and... nothing improves. Or worse, it does improve, in staging, on a table one-hundredth the production size, and you've learned the wrong lesson.

Reading a query plan is a skill with maybe six core concepts. Once you have them, the plan shows exactly where the time goes, and you can fix the slow node directly.

Getting a Plan Worth Reading

Three variants, in increasing usefulness:

-- Estimates only, does not execute
EXPLAIN SELECT ...;

-- Executes the query, adds actual times and row counts
EXPLAIN ANALYZE SELECT ...;

-- What you actually want: adds page-level I/O accounting
EXPLAIN (ANALYZE, BUFFERS) SELECT ...;

On PostgreSQL 18 and later, ANALYZE turns on BUFFERS automatically, so plain EXPLAIN ANALYZE already shows the page counts.

Two warnings before you paste plans into tickets:

  • EXPLAIN ANALYZE really executes the statement. For an UPDATE or DELETE, wrap it: BEGIN; EXPLAIN (ANALYZE, BUFFERS) UPDATE ...; ROLLBACK;
  • Run it against production-sized data. The planner's choices depend on table sizes and statistics; a plan from a 10,000-row dev database tells you nothing about the 80-million-row production table.

If the slow query originates in EF Core, capture the exact SQL first (logging SQL queries in EF Core) and explain that, including its parameters.

The Anatomy of a Plan Node

Take a realistic example:

EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.total
FROM orders o
WHERE o.customer_id = 4821
  AND o.created_at >= now() - interval '90 days';
Index Scan using ix_orders_customer_id on orders o
    (cost=0.56..1245.10 rows=312 width=24)
    (actual time=0.041..2.183 rows=1847 loops=1)
  Index Cond: (customer_id = 4821)
  Filter: (created_at >= (now() - '90 days'::interval))
  Rows Removed by Filter: 3102
  Buffers: shared hit=1210 read=38
Planning Time: 0.310 ms
Execution Time: 2.499 ms

This is the PostgreSQL 17 output format. PostgreSQL 18 prints actual row counts with two decimals (rows=1847.00) and adds an Index Searches line under index scans.

Decode line by line:

  • cost=0.56..1245.10: the planner's estimates in abstract units, startup cost and total cost. Only meaningful for comparing strategies, never as milliseconds.
  • rows=312 vs actual rows=1847: the planner expected 312 rows and got 1,847, a ~6x underestimate. Small errors are normal; order-of-magnitude errors cause bad plans upstream.
  • actual time=0.041..2.183: milliseconds to first row and to completion, per loop.
  • loops=1: how many times this node ran. Multiply actual time by loops to get real cost; this is a common misreading, and it matters most under nested loops.
  • Rows Removed by Filter: 3102: the index found 4,949 rows by customer, then 3,102 were discarded by the date filter. That's wasted work the index didn't cover.
  • Buffers: shared hit=1210 read=38: 1,210 pages served from cache, 38 from disk. Each page is 8KB.

That "Rows Removed by Filter" line is already a finding: a composite index on (customer_id, created_at) would let the index satisfy both conditions and skip the discarded rows. Choosing composite key order and knowing when it pays is its own topic; I covered it in PostgreSQL indexes for .NET developers.

Seq Scan Is Not a Bug, and Index Scan Is Not a Fix

The reflex "Seq Scan = missing index" fails in both directions.

When a seq scan is correct: Suppose a query returns 40% of a table. An index scan would jump between index pages and scattered heap pages, reading many pages twice; a sequential scan reads every page exactly once, in order, which disks and caches handle best. The planner does this arithmetic with real statistics; on small tables or low-selectivity predicates, the seq scan is the optimization. I demonstrated the same kind of gap between intuition and the optimizer's cost model in debunking the "filter early, JOIN later" SQL myth.

A seq scan is a problem when you have a large table, a highly selective predicate (returns 0.1% of rows), and no index that can serve it. The plan then shows huge Buffers and a large Rows Removed by Filter count on the scan node, while its actual rows (the rows that passed the filter) stays small.

When an index scan is the problem: An index scan inside a nested loop with loops=12000 means twelve thousand separate index lookups. Each lookup is fast, but together they add up to the entire query time. The fix is usually not a better index but a better join strategy (or fixing the estimate that made the planner choose nested loop for 12,000 rows when it expected 3).

The three join strategies and when they're right:

  • Nested Loop: right for small outer row counts with an index on the inner side; catastrophic when the outer side is unexpectedly large
  • Hash Join: right for joining big unsorted sets; watch for Batches: >1 in the plan, which means the hash spilled to disk (work_mem too small)
  • Merge Join: right when both inputs are already sorted, typically by an index

You rarely choose these directly; you fix the row estimates and the planner chooses correctly.

BUFFERS: Where the Time Physically Goes

Timing tells you which node is slow; buffers tell you why:

  • shared hit: pages found in PostgreSQL's cache. High hit counts with slow times mean CPU-bound processing (sorting, hashing, filtering millions of cached rows).
  • shared read: pages from disk (or OS cache). High read counts mean real I/O; the second run of the same query being 10x faster confirms it.
  • temp read/written: the query spilled to temp files. Look for Sort Method: external merge Disk: 48200kB on sort nodes; a sort or hash that fits in work_mem is often much faster.

A query that touches 200,000 buffers to return 50 rows is doing 1.5GB of page access for a handful of results. Whatever the node types are, that ratio is the problem; the fix is an index, a better predicate, or a schema that co-locates the needed rows (partitioning, covering indexes, or pre-aggregation).

Why Are the Row Estimates Wrong?

Bad plans usually come from bad estimates. The planner estimated 3 rows, chose a nested loop, got 40,000 rows, and your query took 30 seconds.

Compare rows= with actual rows= at each node, working bottom-up; find the first node where they diverge badly. Then:

-- Refresh statistics for the table
ANALYZE orders;

-- For skewed columns, collect finer-grained stats
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 500;
ANALYZE orders;

-- For correlated columns the planner assumes independent
CREATE STATISTICS orders_customer_status (dependencies)
    ON customer_id, status FROM orders;
ANALYZE orders;

With correlated columns, the planner still multiplies selectivities as if predicates were independent. WHERE country = 'DE' AND city = 'Berlin' gets estimated as (fraction DE) x (fraction Berlin), wildly underestimating, because every Berlin row is a DE row. Extended statistics exist precisely for this.

Autovacuum normally keeps statistics fresh, but bulk loads and large deletes can leave them stale at exactly the moment you're testing. If a plan looks wrong right after a data migration, run ANALYZE before doing anything else.

A Reading Workflow

My order of operations for any slow query, whether it came from a dashboard or an EF Core query that degraded:

Plan-reading workflow: run EXPLAIN ANALYZE BUFFERS on production data, find the node with the largest actual time times loops, then fix statistics if row estimates are far off or fix the access path if buffers are huge for few rows, and re-run comparing execution time
  1. EXPLAIN (ANALYZE, BUFFERS) on production-scale data.
  2. Find the node where actual time x loops is largest. That's the bottleneck; ignore everything else for now.
  3. Check its estimate vs actual rows. If it's off by 10x or more, fix statistics first; that alone may change the plan.
  4. Check its buffers. Massive page counts for few output rows means an access-path problem (index, predicate, layout). Temp files mean work_mem.
  5. Only now consider an index, and design it to cover the full predicate (watch "Rows Removed by Filter" go to zero).
  6. Re-run and compare end-to-end Execution Time.

For plans too large to read raw, paste the output into explain.depesz.com or explain.dalibo.com; they compute the per-node exclusive times for you.

Summary

EXPLAIN (ANALYZE, BUFFERS) answers four questions, and reading a plan is just asking them in order:

  • Where did the time go? The node with the largest actual time x loops.
  • Was the planner's model right? Estimated vs actual rows; large gaps point to stale or coarse statistics.
  • Is it I/O or CPU? Buffers: reads and temp files vs cache hits.
  • Is the access path proportionate? Pages touched vs rows returned.

Judge each scan node by its actual time, rows, and buffers. Fix estimates before strategies, and verify with the same command you diagnosed with.

Frequently Asked Questions

What is the difference between EXPLAIN and EXPLAIN ANALYZE in PostgreSQL?

EXPLAIN shows the plan the optimizer chose with estimated costs, without running the query. EXPLAIN ANALYZE executes the query and adds actual times, actual row counts, and loop counts, which is what you need to find real bottlenecks.

Is a sequential scan always bad?

No. For small tables, or queries that return a large fraction of a table, a sequential scan is the fastest strategy and the optimizer picks it deliberately. A seq scan is only a problem when it reads far more rows than the query returns on a large table.

What does the BUFFERS option show in EXPLAIN ANALYZE?

It reports how many 8KB pages each node touched, split into shared hit (found in the PostgreSQL buffer cache) and read (fetched from the OS cache or disk). It shows whether a slow query is doing real I/O or just processing a lot of cached data. On PostgreSQL 18 and later, EXPLAIN ANALYZE includes buffer counts by default.

Why are the row estimates in my query plan wrong?

The planner relies on table statistics that may be stale or too coarse. Running ANALYZE refreshes them, and raising the statistics target or creating extended statistics helps with skewed or correlated data. Large estimate errors lead to bad join strategies.

  • Why Postgres Ignores Your Index (Sargability, Taught by a Kata)

    Your query is correct and your tests pass, but the index you created is never touched. The usual culprit is wrapping the column in a function. Here is what sargability means, how to catch the problem with EXPLAIN, and how I built a coding kata that grades your query plan.

  • PostgreSQL Indexing for .NET Developers

    B-tree indexes cover most of your queries. Learn when GIN, partial, and covering indexes beat a plain B-tree for the rest, and how to configure each one from EF Core so it survives your migrations.

  • PostgreSQL Table Partitioning for .NET Applications

    DELETE FROM on a 500 million row table runs for hours and leaves the table bloated. Dropping a partition takes milliseconds. Here is when PostgreSQL partitioning pays off, how to set it up, and how to use it from EF Core.

Browse all Databases guides →
Loading comments...

Whenever you're ready, there are 5 ways I can help you:

  1. Pragmatic Self-Hosting: Learn to deploy and run your apps on a VPS with Dokploy and Tailscale. Keep administration private, automate releases, and practice restoring backups, with source code and a runbook you can reuse.
  2. Pragmatic Clean Architecture: Join 5,000+ students in this comprehensive course that will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture.
  3. Modular Monolith Architecture: Join 2,800+ engineers in this in-depth course that will transform the way you build modern systems. You will learn the best practices for applying the Modular Monolith architecture in a real-world scenario.
  4. Pragmatic REST APIs: Join 1,900+ students in this course that will teach you how to build production-ready REST APIs using the latest ASP.NET Core features and best practices. It includes a fully functional UI application that we'll integrate with the REST API.
  5. Patreon Community: Join a community of 5,000+ engineers and software architects. You will also unlock access to the source code I use in my YouTube videos, early access to future videos, and exclusive discounts for my courses.

The .NET Weekly

One practical .NET tip, every Saturday.

Join 66,000+ engineers who read it. Free, and you can unsubscribe any time.