Every engineer eventually meets the same ghost: a query that was fast last week and is inexplicably slow today. The tool that tells you why is EXPLAIN ANALYZE — and most people read its output wrong, skimming for a big number and guessing. Read properly, a Postgres query plan is a precise, honest account of exactly what the database did and where the time went. This is how to read one like you mean it, using a real slow-query hunt — including the kind that shows up in an AI app — as the worked example.
We’ll cover why BUFFERS is non-negotiable, the single comparison that solves most slow queries, how to read the plan tree, and the two always-on tools (pg_stat_statements and auto_explain) that find the query worth explaining in the first place.

🔎 EXPLAIN vs. EXPLAIN ANALYZE (and Why BUFFERS Isn’t Optional)
Plain EXPLAIN shows the plan the optimizer intends to run, with cost estimates — useful, but it’s a prediction. EXPLAIN ANALYZE actually executes the query and reports the real per-node timing and row counts alongside the estimates. That’s the version you almost always want.
The piece people skip is BUFFERS. Add it — EXPLAIN (ANALYZE, BUFFERS) — and Postgres tells you how many 8 KB pages each node read from cache (shared hit) versus fetched from disk (shared read), plus what it dirtied and wrote. Raw timing tells you a node was slow; buffers tell you whether that was CPU, a cache hit, or an actual disk read — which is usually the difference between “add an index” and “this query is fine, the data’s just cold.” Make EXPLAIN (ANALYZE, BUFFERS) your default habit, not a special occasion.
One safety note: because ANALYZE runs the statement, explaining an UPDATE/DELETE/INSERT performs it. Wrap anything that writes in a transaction you intend to roll back.
🧭 Estimated vs. Actual: The First Thing to Look At
The Postgres planner is cost-based: it chooses a plan by estimating how many rows each step will produce, using statistics gathered by ANALYZE. Almost every mysterious slow query traces back to those estimates being wrong.
So the single most useful thing you can do with a plan is compare, on each node, the estimated row count against the actual one:
Seq Scan on chunks (cost=0.00..18234.00 rows=1000 width=512) (actual time=0.02..842.11 rows=250000 loops=1)The planner expected rows=1000; reality was rows=250000. That 250× gap is the smoking gun. The planner made a bad choice (here, a sequential scan) because it was working from a wrong estimate — usually stale statistics after a bulk load, a column whose values are correlated in ways single-column stats can’t model, or a table that was never ANALYZEd. Fix the estimate (run ANALYZE, add extended statistics, or reconsider the index) and the plan often fixes itself. Chase the biggest estimated-vs-actual divergence first; it’s right far more often than staring at timings.

🧱 Reading the Plan Tree
A plan is a tree, and it executes from the inside out — the most indented nodes run first, feeding their parents. Read it bottom-up.
A few nodes cover most cases. A Seq Scan reads the whole table; fine for small tables or when you genuinely need most rows, a red flag on a large table you’re filtering hard. An Index Scan walks an index to fetch specific rows; a Bitmap Heap Scan is Postgres’s middle ground when an index matches many rows. Joins come in three shapes: Nested Loop (great when one side is tiny), Hash Join (the workhorse for larger unsorted sets), and Merge Join (for pre-sorted inputs). One number people misread: loops=. A node showing actual time=5ms with loops=1000 didn’t take 5ms — it ran a thousand times. Multiply.

You don’t need to memorize every node type. You need to find the node where time actually accumulates (watch for a costly node with high loops, or a Seq Scan feeding a huge row count upward) and ask why the planner chose it.
🩺 Finding the Query Worth Explaining: pg_stat_statements
You can’t EXPLAIN a query you haven’t identified. pg_stat_statements is the extension that makes that possible: it aggregates execution statistics across every run of every query, so you can rank by total time and find the handful of statements actually consuming your database. It’s the always-on baseline every serious Postgres deployment should run.
It needs to be loaded via shared_preload_libraries (which means a restart — that’s the real adoption friction, not the usage). Two knobs, track_planning and track_io_timing, are off by default because they add measurable overhead; turn them on deliberately when you’re specifically chasing planning-time or I/O regressions, not as a matter of course. The overhead is real and workload-dependent, so benchmark on your own hardware rather than trusting a number from a blog.
🎯 Catching Slow Queries in Production: auto_explain
pg_stat_statements tells you which query is slow; auto_explain captures the plan of slow statements automatically, in production, with no application changes. Set a log_min_duration threshold (say, 3 seconds) and any statement crossing it gets its plan written to the log — including the plan that ran during the incident, which you can never reproduce afterward from a quiet database.
The catch is the same as everywhere else: turning on log_analyze (to capture actual, not just estimated, rows) adds per-statement overhead, so leave it off except during a targeted investigation, and use sample_rate to throttle logging on hot paths. Like the others, it loads via shared_preload_libraries.

🧠 A Worked Example: A Slow Retrieval Query in an AI App
Put it together with a case straight from a retrieval-augmented-generation app. Users complain that “search my documents” got sluggish. pg_stat_statements ranks the culprit by total time: a query that fetches the nearest document chunks for a given user, filtered to that user’s documents.
You run EXPLAIN (ANALYZE, BUFFERS) and the plan tells the whole story. The estimated-vs-actual gap is huge on the chunk table, and — the real find — the pgvector similarity search isn’t using its HNSW index at all; it’s a Seq Scan computing distance against every row. The cause is a classic one covered in the vector-search guide: the index was built with the wrong operator class for the query’s distance operator, so the planner silently fell back to scanning. Rebuild the index with the matching operator class, run ANALYZE so the planner’s estimates reflect reality, and the plan flips to an index scan. The BUFFERS line confirms the win — reads drop from hundreds of thousands of pages to a handful.
The lesson generalizes: the plan didn’t just say “slow,” it said exactly which assumption was false. That’s what makes EXPLAIN ANALYZE worth learning properly rather than skimming.
📈 Beyond One Query: Partitioning and the Columnar Question
Sometimes the plan proves the query is fine and the table is the problem — it’s simply too big for any single index to save. Two escalations, in order.
Partitioning splits one giant table into many by a key (usually time). When a query filters on that key, Postgres skips the irrelevant partitions entirely — “partition pruning.” The important caveat: pruning is the mechanism, not the magic. You only get the 10–100× win when the query actually filters on the partition key; a query that doesn’t gets no benefit and a little overhead. Pick the partition key from your real access pattern. On huge append-mostly tables, a BRIN index is a near-free companion — tiny, and excellent when the column is physically correlated with insert order (like a timestamp), useless when it isn’t.
When row storage itself is the wrong shape for heavy analytical scans, there’s a columnar-on-Postgres landscape — Citus, TimescaleDB, pg_duckdb. Here’s the honest warning, though: this niche churns fast. In roughly a year, the startup Hydra shut down and ParadeDB archived its original analytics extension. Before you build on any of these, check the project’s recent GitHub activity — don’t trust a name you read in an article (including this one) as proof it’s still maintained.

🧮 Measuring the AI System, Not Just the Query
Postgres is also a fine place to store what you measure about an AI system — eval traces, per-request token and cost accounting (tools like LiteLLM write usage straight to a Postgres table), and retrieval-quality metrics like precision@k over a labeled set. For a lot of teams that’s all the observability they need.
But know the ceiling before you hit it. The canonical open-source LLM-observability stack (Langfuse) deliberately puts Postgres in charge of transactional metadata — projects, prompts, scores — and routes the high-volume trace firehose to a columnar store (ClickHouse). If you’re logging every model call to a Postgres table, that split is worth anticipating rather than discovering under load.
🧭 What This Means for You
Build the habit: EXPLAIN (ANALYZE, BUFFERS) by default, and read estimated vs. actual rows before anything else — it points at the real cause more often than timings do. Keep pg_stat_statements on as your baseline so you always know your worst queries, and add auto_explain so production slow-downs leave evidence. Don’t reach for partitioning or a columnar extension until a plan has proven a single query genuinely can’t be fixed with statistics and an index. And because overhead and behavior shift between versions, benchmark on your own environment instead of trusting a fixed number — including the ones here.
📚 Further Reading
- Why Postgres Became the Default Database for AI Apps — the cornerstone this performance work sits under.
- Is Postgres a Real Vector Database? — including the operator-class trap behind the worked example above.
- Postgres as Your Entire AI Backend — where the queries you’re profiling actually live.
- Primary sources: PostgreSQL docs on Using EXPLAIN, auto_explain, and pg_stat_statements.
❓ Frequently Asked Questions
What’s the difference between EXPLAIN and EXPLAIN ANALYZE?
EXPLAIN shows the plan the optimizer intends to use, with estimates only. EXPLAIN ANALYZE actually runs the query and reports real timing and row counts next to the estimates. Use EXPLAIN (ANALYZE, BUFFERS) for the full picture — and remember ANALYZE executes the statement, so wrap writes in a rollback.
Why does BUFFERS matter so much?
Timing alone can’t tell you whether a node was slow because of CPU work, a cache hit, or a real disk read. BUFFERS reports pages read from cache versus disk, which is usually what tells you whether a query needs an index or just had cold data.
What should I look at first in a query plan?
The gap between estimated rows and actual rows on each node. A large divergence means the planner made its choice from bad statistics — the most common root cause of a suddenly-slow query. Fix the statistics (or the index) before anything else.
How do I find which query to EXPLAIN?
Use pg_stat_statements, which aggregates timing across all executions so you can rank queries by total time. Pair it with auto_explain to automatically capture the plans of slow statements in production.
When should I partition instead of adding an index?
When the table is so large that no index helps and your queries filter on a natural key (usually time). Partitioning lets Postgres skip irrelevant partitions — but only when the query filters on the partition key. If it doesn’t, partitioning won’t help.
📚 Recommended Resources
Disclosure: some links below are Amazon affiliate links. If you buy through them, I earn a small commission — at no extra cost to you — which helps keep this site running.
SQL Performance Explained
Markus Winand · Book · ~$40 on Amazon
The clearest short book on why queries are slow and how indexes actually work — the perfect companion to reading a query plan. If you internalize one book on this topic, make it this one.
Database Internals
Alex Petrov · Book · ~$55 on Amazon
Goes under the plan to the storage engines, B-trees, and buffer pools that the BUFFERS numbers are actually reporting on — so the output stops being mysterious.
PostgreSQL Query Optimization
Henrietta Dombrovskaya, Boris Novikov & Anna Bailliekova · Book · ~$50 on Amazon
A Postgres-specific, hands-on guide to building efficient queries and reading the planner — the natural next step once you’re comfortable with EXPLAIN ANALYZE.