# Diagnosing Slow PostgreSQL Queries with EXPLAIN ANALYZE and BUFFERS

> How to find and fix a slow PostgreSQL query: read EXPLAIN (ANALYZE, BUFFERS), check row estimates, then choose indexes, statistics and query shape to match.

- Author: Zeeshan Adil (https://www.internalswithzee.com/about)
- Published: 2025-10-20
- Updated: 2026-11-16
- Source: https://www.internalswithzee.com/blog/postgresql-optimization

## The short version

- Run EXPLAIN (ANALYZE, BUFFERS), then compare estimated rows with actual rows. A big gap can lead the planner to choose a poor plan.
- A sequential scan is not a bug. It is the right plan when a query reads a large share of the table, and the planner picks it on cost.
- In Buffers, shared hit came from PostgreSQL's cache and shared read did not. Many reads on a hot query is worth a look.
- Find the queries worth tuning with pg_stat_statements, change one thing at a time, and measure again on production-like data.

A query that used to be quick can become the bottleneck as a table grows, traffic changes, or PostgreSQL chooses a plan based on a bad estimate. The execution plan helps you decide whether an index would help and, if so, which one to add.

Here's how I approach a slow query: find where the time goes, compare what the planner expected with what actually happened, and measure the effect of each change.

The examples below are a way to read what PostgreSQL is telling you, not a list of indexes to add blindly.

## Start with EXPLAIN (ANALYZE, BUFFERS)

Before optimizing anything, understand what the query is actually doing:

```sql
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.id, o.status, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.created_at > '2025-01-01'
  AND o.status = 'pending'
ORDER BY o.created_at DESC
LIMIT 100;
```

Plain `EXPLAIN` shows the plan the planner would pick and its estimates. Adding `ANALYZE` actually runs the query and reports what really happened. That has a consequence: `EXPLAIN ANALYZE` on an `UPDATE`, `DELETE` or `INSERT` really changes data. Wrap it in a transaction and roll back:

```sql
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders SET status = 'archived' WHERE created_at < '2024-01-01';
ROLLBACK;
```

A rollback protects transactional database changes, but it doesn't make the experiment free: the statement still takes locks and consumes resources, and side effects such as sequence increments or external calls may not be undone. Use a safe environment and representative data when possible.

Adding `BUFFERS` shows how many buffer accesses each node reports. Timing can vary between runs; buffer counts also depend on the plan, cache state, and data, but they help you see how much work the query did. PostgreSQL normally uses 8 kB pages.

Here is what a node looks like. This is an illustrative plan with made-up numbers, only to show where to look:

```text
Index Scan using idx_orders_status_created on orders o
    (cost=0.43..8120.50 rows=900 width=24)
    (actual time=0.05..41.20 rows=96000 loops=1)
  Index Cond: ((status = 'pending') AND (created_at > '2025-01-01'))
  Buffers: shared hit=1200 read=5300
```

Read it in this order:

1. `rows=900` is the estimate. `rows=96000` is what actually came back. A gap that large means the planner chose its plan believing something false.
2. `shared hit=1200` pages were found in PostgreSQL's shared buffer cache. `read=5300` were not, so PostgreSQL asked the operating system for them. The OS may still have served them from its own page cache, so a "read" is not always a disk read. Compare repeated runs, bearing in mind that a higher hit count on the second run can indicate the first warmed PostgreSQL's cache; it doesn't tell you exactly what was on disk.
3. `loops` multiplies. A node with a small time and `loops=50000` is where a nested loop is quietly costing you. The reported time and rows are per loop.

Key things to look for:

- **Seq Scan vs Index Scan**: Neither is better by default. A sequential scan is the right plan when the query reads a large share of the table, because reading pages in order is cheaper than jumping through an index for most of the rows. It is a problem when the query wants a few rows and the plan still reads everything. Judge it by rows returned against rows scanned.
- **Estimated rows vs actual rows**: Big differences mean the planner is working from a wrong picture. Stale statistics are one cause. Others are skewed data, correlated columns, and expressions it has no statistics for.
- **Buffers**: How many pages came from cache (`hit`) versus outside it (`read`), and `dirtied` or `written` for writes. A query that reads thousands of pages to return a handful of rows is doing too much work, whatever the timing says.
- **Loops**: Nested loops with high iteration counts.
- **Sort and hash nodes**: Look for `Sort Method: external merge  Disk:`. It means the sort did not fit in `work_mem` and spilled to temporary files (more on that below).

![In the illustrative plan above, the planner estimates 900 rows and the scan returns 96,000 rows in one loop, about 107 times more. The mismatch can affect plan choice and is a reason to investigate statistics, data distribution and query shape.](https://www.internalswithzee.com/images/diagrams/query-row-estimate-wide.svg)

## Query Optimization at Scale

In one project involving a microservices-based bidding platform, we had bulk API calls that needed optimization. One query looked innocent:

```sql
SELECT v.*, 
       (SELECT COUNT(*) FROM bids WHERE vehicle_id = v.id) as bid_count,
       (SELECT MAX(amount) FROM bids WHERE vehicle_id = v.id) as highest_bid
FROM vehicles v
WHERE v.auction_id = $1;
```

The problem: correlated subqueries run once per row. With 500 vehicles per auction, that is 1,000 subquery executions inside a single statement. Each one is cheap if `bids(vehicle_id)` is indexed, and expensive if it is not. The plan shows them as `SubPlan` nodes with a large `loops` count, which is exactly the signal to look for.

Through query optimization, we achieved up to 13x performance improvements, bringing most queries under 50ms.

The fix: aggregate once instead of once per row. Restrict the aggregation to the vehicles you need, otherwise you aggregate every bid in the table:

```sql
SELECT v.*, 
       COALESCE(b.bid_count, 0) as bid_count,
       b.highest_bid
FROM vehicles v
LEFT JOIN (
    SELECT vehicle_id, 
           COUNT(*) as bid_count, 
           MAX(amount) as highest_bid
    FROM bids
    WHERE vehicle_id IN (SELECT id FROM vehicles WHERE auction_id = $1)
    GROUP BY vehicle_id
) b ON b.vehicle_id = v.id
WHERE v.auction_id = $1;
```

Result in that project: under 1 second. Those figures come from that project's data and indexes. They are not a benchmark of the queries above, and yours will differ. A `LATERAL` join is another reasonable shape, and with an index on `bids(vehicle_id)` it can win when only a few vehicles are involved. Check with `EXPLAIN (ANALYZE, BUFFERS)` rather than assuming.

## Index Strategies

Indexes aren't free. They speed up reads but slow down writes, and they take space. Here's how I think about them:

**Composite indexes**: Column order matters. A useful starting point is equality columns first, then the range or sort column. Conditions on leading columns usually narrow the scan most effectively. Later columns can still filter index entries, and PostgreSQL 18 can sometimes use skip scan to reduce the work even when a leading column isn't constrained. Check the plan and the workload rather than relying on a fixed rule.

```sql
-- Good for: WHERE status = 'pending' AND created_at > '2025-01-01'
-- status is an equality, created_at is a range, so status goes first
CREATE INDEX idx_orders_status_created ON orders(status, created_at);

-- Less useful if you often query by created_at alone,
-- because the leading column is status
-- Consider a separate index
```

**Partial indexes**: Index only what you need.

```sql
-- Illustrative: if pending orders are a small slice of the table
-- but most of your queries ask about them, index only that slice
CREATE INDEX idx_orders_pending ON orders(created_at)
WHERE status = 'pending';
```

The query has to include `status = 'pending'` (or something that implies it) for the planner to use this index. The payoff depends on how small that slice really is, so check the share with a `COUNT` first.

**Covering indexes**: Include columns to avoid table lookups.

```sql
-- Includes customer_name and total so the query can be answered
-- from the index alone (an index-only scan)
CREATE INDEX idx_orders_covering ON orders(status, created_at)
INCLUDE (customer_name, total);
```

An index-only scan checks the visibility map to see whether a heap page's rows are known to be visible to all transactions. If the table has many recently changed pages that vacuum has not processed, you will see `Heap Fetches` in the plan and the index buys you less. That is one more reason vacuum matters for read speed.

## Common Anti-Patterns

**Functions on indexed columns**:

```sql
-- Bad: Can't use a plain index on created_at
WHERE DATE(created_at) = '2025-01-15'

-- Good: Index-friendly range
WHERE created_at >= '2025-01-15' AND created_at < '2025-01-16'
```

If you cannot rewrite the query, an expression index can help when the indexed expression is immutable and matches the query. For a `timestamptz` column, the date depends on the time zone: choose an explicit time zone and use the same expression in the index and query.

**OR conditions**:

```sql
-- Same filtering meaning; PostgreSQL may choose different execution plans
WHERE status = 'pending' OR status = 'processing'
WHERE status IN ('pending', 'processing')

-- Different columns: this can be slow, or can use a BitmapOr over two indexes
WHERE status = 'pending' OR customer_id = 42
```

`IN` is easier to read and to extend, but for the same column the planner already handles both forms alike. An `OR` across different columns is the one worth checking: it may need an index on each column to use a bitmap OR, or may be better as separate queries combined with `UNION ALL`. Preserve the original semantics: if a row can match both branches, `UNION ALL` returns it twice. Look at the plan.

**LIKE with leading wildcard**:

```sql
-- Can't use a regular B-tree index
WHERE email LIKE '%@gmail.com'

-- Option 1: trigram index (needs the pg_trgm extension)
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_email_trgm ON users USING gin(email gin_trgm_ops);

-- Option 2: for suffix matches, index the reversed string
CREATE INDEX idx_email_rev ON users (reverse(email) text_pattern_ops);
-- and query: WHERE reverse(email) LIKE 'moc.liamg@%'
```

Also note that a plain `LIKE 'abc%'` (prefix match) only uses a B-tree index if the index was built with `text_pattern_ops`, or the column uses the `C` collation.

**Deep OFFSET pagination**:

```sql
-- Reads and throws away the first 100000 rows on every call
SELECT * FROM orders ORDER BY created_at, id LIMIT 50 OFFSET 100000;

-- Keyset pagination: remember where the last page ended
SELECT * FROM orders
WHERE (created_at, id) > ($1, $2)
ORDER BY created_at, id
LIMIT 50;
```

`OFFSET n` has to produce and discard `n` rows, so page 2,000 costs far more than page 1. Keyset pagination, backed by an index on `(created_at, id)`, costs about the same for every page. The tradeoff is that you can go to the next page easily but cannot jump straight to page 2,000.

## Analyzing Production Queries

PostgreSQL's `pg_stat_statements` extension is invaluable. It has to be loaded first: add it to `shared_preload_libraries` (this needs a restart), then run `CREATE EXTENSION pg_stat_statements;` in the database.

```sql
SELECT query,
       calls,
       mean_exec_time,
       total_exec_time,
       rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
```

This shows you where time is actually spent, not where you think it's spent. Sorting by `total_exec_time` finds the queries that cost the most in aggregate. Sorting by `mean_exec_time` finds the slow individual ones. You usually want both lists, and then `EXPLAIN (ANALYZE, BUFFERS)` on the top few.

## Statistics and Planner

Sometimes the query plan is bad because PostgreSQL's statistics are out of date or too coarse. Autovacuum normally runs `ANALYZE` for you in the background, so stale statistics most often show up right after a bulk load or a big change in the data, before autovacuum has caught up:

```sql
-- Update statistics for a table
ANALYZE orders;

-- Check when stats were last updated
SELECT relname, last_analyze, last_autoanalyze
FROM pg_stat_user_tables
WHERE relname = 'orders';
```

Two different problems need two different tools. If one column has a very skewed distribution and the planner's estimates for it are poor, raise the statistics target for that column:

```sql
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;
ANALYZE orders;
```

If two or more columns are correlated, so that filtering on both together does not shrink the result the way multiplying their separate selectivities would suggest, use extended statistics:

```sql
CREATE STATISTICS orders_stats (dependencies)
ON status, priority FROM orders;
ANALYZE orders;
```

Extended statistics are only filled in by the next `ANALYZE`, so run it after creating them.

## work_mem and sorts

`work_mem` is a base memory limit for operations such as sorts and hashes before they may spill to temporary files. Hash operations can use `work_mem` multiplied by `hash_mem_multiplier`. Multiple operations, concurrent sessions, and parallel workers can use many multiples of the setting. That is why raising it globally is risky. If an `EXPLAIN (ANALYZE, BUFFERS)` shows an external merge sort on disk for one important query, try raising it for that session or role first and measure:

```sql
SET work_mem = '64MB';  -- this session only; pick the value by testing
```

A `temp read=... written=...` entry in the `Buffers` line is another way to see spilling.

## Connection Pooling

Not strictly query optimization, but connection overhead adds up. PostgreSQL runs one backend process per connection, and each one uses memory. The amount depends on the workload (sorts, caches, prepared statements), so there is no single number to plan with. Measure it on your system. Hundreds or thousands of mostly idle connections still cost memory and add contention. With high concurrency:

- Use PgBouncer or similar pooler
- Transaction pooling mode for most workloads, with one catch: anything that depends on a session breaks, such as `SET` without `LOCAL`, session-level advisory locks, `LISTEN`, and some temporary-table uses. `NOTIFY` itself is supported in transaction pooling; check your pooler version's rules on prepared statements and other session features too.
- Session pooling only when you need session state

## Vacuum, bloat and plans

A table with many dead row versions is bigger than its live data, so scans read more pages for the same result. Autovacuum is on by default and is usually enough, but a table with heavy updates or deletes can outrun it. Watch `n_dead_tup` in `pg_stat_user_tables`, and check autovacuum settings per table when a hot table keeps bloating. `VACUUM` marks space as reusable and keeps the visibility map current, which index-only scans rely on. It does not usually shrink the file. Rebuilding a bloated index is a separate step, and `REINDEX CONCURRENTLY` does it without blocking writes.

## Lessons Learned

1. **Measure first**: Don't guess where the problem is
2. **Test with production-like data**: Query plans change with data volume and data distribution, so a plan on a small test table can mislead you
3. **Monitor continuously**: Performance degrades as data grows
4. **Index maintenance**: Rebuild indexes when you have measured bloat, not on a calendar

Query optimization is iterative. Make one change, measure, repeat. The goal isn't the perfect query. It's a query that meets your performance requirements with acceptable maintenance overhead.

## Sources and further reading

The reference material behind everything above, in the order I would read it.

- [PostgreSQL: Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html). What every node in a plan means, and the difference between estimated and actual rows, which is where most mysteries resolve.
- [PostgreSQL: Statistics used by the planner](https://www.postgresql.org/docs/current/planner-stats.html). Why the planner chose what it chose, and what to do when its row estimates are badly wrong.
- [PostgreSQL: Index types](https://www.postgresql.org/docs/current/indexes-types.html). B-tree, hash, GiST, GIN and BRIN, and the access patterns each one is actually for.
- [PostgreSQL: pg_stat_statements](https://www.postgresql.org/docs/current/pgstatstatements.html). The extension that tells you which queries cost the most in aggregate, which is rarely the one somebody complained about.
- [PostgreSQL: Resource consumption settings](https://www.postgresql.org/docs/current/runtime-config-resource.html). What `work_mem` does and why it applies per node.
- [Use The Index, Luke](https://use-the-index-luke.com/) by Markus Winand. The clearest explanation anywhere of how a B-tree index is actually used, and why column order in a composite index decides whether it helps at all. It also covers keyset pagination.
- [explain.depesz.com](https://explain.depesz.com/). Paste a plan, see where the time really went. Faster than reading nested plan output by eye.
- [PgBouncer features](https://www.pgbouncer.org/features.html), for the pooling section, including the table of what transaction pooling breaks.

## Continue learning

For a wider view of the machine behind your queries, read [Aurora Serverless v2 to Self-Managed PostgreSQL](/blog/self-managed-postgresql-from-first-principles). It covers memory, storage, vacuum, and how to measure a workload before sizing a database. To go deeper into individual plans, investigate row estimates and index-only scans alongside visibility maps.

## FAQ

**Why is my index being ignored?**
Usually because the planner expects to touch a large fraction of the table, where a sequential scan genuinely wins. Sometimes because a function or type cast on the column makes the index unusable, or because the leading column of a composite index is not in your filter. Check the estimated rows first. On fast SSD storage, also look at whether `random_page_cost` still reflects your hardware.

**Should I add an index for every slow query?**
No. Indexes consume space and can add work to inserts and updates, especially when indexed values change. Look for one index that serves several queries. Before dropping an apparently unused index, check whether it enforces a constraint or supports infrequent but important operations, and make sure your observation window is representative.

**How do I find the queries that actually matter?**
`pg_stat_statements`, ordered by total time rather than mean time. A query taking 20ms ten thousand times an hour costs far more than a 2 second report nobody runs twice.
