Skip to main content
Postgres Query Plans: Reading Them and the Indexes We Wish We'd Added Sooner

Postgres Query Plans: Reading Them and the Indexes We Wish We'd Added Sooner

KU
· Founder & Chief Editor
• 8 min read•Updated •

EXPLAIN ANALYZE output is dense and intimidating. Once you can read it, most slow-query investigations finish in minutes. The patterns we keep seeing.

Key takeaways

  • Run EXPLAIN (ANALYZE, BUFFERS) on the slow query and find the node with the highest actual time multiplied by loops.
  • Its shape names the fix: a seq scan wants an index, a disk sort wants more work_mem, a function on the column wants an expression index.
  • Build indexes with CREATE INDEX CONCURRENTLY in production.

To fix a slow Postgres query, run EXPLAIN (ANALYZE, BUFFERS) on it, find the plan node with the highest actual time multiplied by loops, and match its shape: a Seq Scan discarding most rows needs an index, an external-merge Sort needs more work_mem, and a function on the column needs an expression index. Then re-run to confirm the plan changed.

Verified against

PostgreSQL 18 (current minor 18.6), against the postgresql.org docs for Using EXPLAIN, EXPLAIN, CREATE INDEX, foreign keys and BRIN indexes. Checked October 2026.

We used to guess at an index, add it, and hope, and often ended up with three useless indexes plus the original problem. Reading the plan replaces the guess with a specific step to fix.

EXPLAIN ANALYZE in one paragraph

EXPLAIN shows the plan Postgres would run. EXPLAIN ANALYZE runs the query and shows actual timings and row counts. Always use ANALYZE in real diagnosis: the planner's estimates can be wildly off, and the actual numbers are what matter. The cost is that ANALYZE executes the query, so wrap anything destructive in a transaction you roll back.

SQL
BEGIN;
EXPLAIN (ANALYZE, BUFFERS) DELETE FROM users WHERE created_at < '2020-01-01';
ROLLBACK;

BUFFERS adds I/O statistics so you can see how much of the plan read from cache versus disk. Since PostgreSQL 18 the docs say buffer information is included automatically with ANALYZE; on 17 and older you still have to ask for it.

How to read the plan

Plans are trees, output bottom-up. The bottom-most node is the leaf (a scan); each level above combines, filters, sorts, joins. The numbers cost=A..B are the planner's startup and total cost estimates; actual time=A..B is real wall-clock time in milliseconds for that node.

The numbers to actually read:

  • actual time at each node: how long that node took.
  • rows at each node: how many rows came out. If actual rows far exceed estimated rows, the planner has bad stats.
  • loops: how many times the node ran. Inside a nested loop join, the inner node runs once per outer row. The docs are explicit that time and rows are per-execution averages; multiply by loops for the real cost.
  • Buffers: shared hit / read: hit is cache, read is disk. Lots of read on a hot query is a problem.

The slow part of the query is the node with the highest actual time × loops. Find that and you've found the bottleneck.

Common patterns we keep seeing

A handful of plan shapes account for most of our slow-query investigations.

Pattern 1: Seq Scan on a big table where you expected an index

code
Seq Scan on orders (cost=0.00..18452.32 rows=10000 width=1000) (actual time=120.5..234.8 rows=8 loops=1)
  Filter: (customer_id = 12345)
  Rows Removed by Filter: 999992

Translation: scanned a million rows, kept 8. Either there's no index on customer_id, the planner wrongly thinks a seq scan is cheaper (stale statistics), or a function or cast makes the index unusable. Most common cause: simply no index. Fix it without blocking writes, then re-run and confirm the plan switched to an Index Scan:

SQL
CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 12345;

Pattern 2: Index Scan that's still slow

code
Index Scan using orders_customer_id_idx on orders (actual time=0.1..1850.3 rows=145000 loops=1)
  Index Cond: (customer_id = 12345)

The index lookup is fine, but it returned 145k rows that the next step has to process. Probably you need a composite index that covers more of the WHERE clause:

SQL
-- Was: WHERE customer_id = ? AND status = 'open'
CREATE INDEX ON orders (customer_id, status) WHERE status = 'open';
-- Partial index: only contains open orders, smaller and faster.

Pattern 3: Nested Loop with high loops

code
Nested Loop (actual time=0.1..14523.8 rows=10 loops=1)
  -> Seq Scan on users (actual time=0.0..52.1 rows=50000 loops=1)
  -> Index Scan using orders_user_id_idx (actual time=0.2..0.3 rows=0 loops=50000)

50,000 outer rows, each looking up orders. The inner scan is fast per loop (0.3ms), but 50,000 loops at 0.3ms is 15 seconds. A hash join would be far cheaper; fresh statistics (ANALYZE the table) usually get the planner there, and occasionally you rewrite the query to nudge it.

Pattern 4: Sort node with disk overflow

code
Sort (actual time=2350.0..3000.0 rows=500000 loops=1)
  Sort Method: external merge  Disk: 250000kB

The sort spilled to disk because it didn't fit in work_mem. Two fixes:

  1. Increase work_mem for the transaction: SET LOCAL work_mem = '256MB' before the query. Don't set it high globally; it applies per sort or hash node, so a query with four sorts can use four times the value.
  2. Avoid the sort entirely: if the ORDER BY matches an index, the index can return sorted output and skip the sort.

The same applies to a Hash node showing Batches: 32: the hash spilled to disk in 32 chunks, and a local work_mem bump usually fixes it.

Pattern 5: Function call kills index usage

SQL
-- This won't use an index on email:
WHERE LOWER(email) = 'foo@example.com'

-- This will, with an expression index:
CREATE INDEX ON users (LOWER(email));

-- Or, if emails are already stored lowercase, drop the function:
WHERE email = 'foo@example.com'

A function on the column side of a WHERE clause blocks a plain index. Common offenders: LOWER, DATE_TRUNC, EXTRACT, and casts like field::int.

The indexes we wish we'd added sooner

Indexes on every foreign key column. The docs state that declaring a foreign key does not automatically index the referencing columns. If you have posts(author_id), you almost certainly want an index on author_id, and your ORM may not add one either, so check.

Partial indexes for "active" rows. Most queries filter on a status or deleted_at IS NULL subset. A partial index on that subset is smaller and the planner uses it for matching queries automatically.

Composite indexes in query order. (tenant_id, status, created_at) for a multi-tenant app: tenant first (always in the WHERE clause), status next, created_at last for the ORDER BY.

BRIN indexes on append-only tables. For very large tables where a column correlates with physical order (events inserted by time), a BRIN index stores one summary per block range, so it is a tiny fraction of a B-tree's size and works well for range scans. We use these for log-like tables.

Things we stopped doing

A few patterns I see teams overdo:

Indexing every column. Every index is updated on every write that touches it, so eight indexes means eight extra structures to maintain per insert. Index for the queries that matter, and watch for index bloat on the ones you keep.

Plain CREATE INDEX during incident response. A standard build locks out writes (not reads) until it finishes. Use CREATE INDEX CONCURRENTLY in production; it cannot run inside a transaction block and can leave an invalid index if it fails, so check and drop that before retrying.

Forgetting to VACUUM ANALYZE after big data changes. After a large insert or delete, stats are stale; the planner makes bad choices. VACUUM ANALYZE table_name updates the stats.

A quick checklist

  1. EXPLAIN (ANALYZE, BUFFERS) the query.
  2. Find the node with the highest actual time times loops.
  3. Identify the shape: seq scan, slow index scan, nested loop, sort or hash spill, function on the column.
  4. Apply the matching fix, then re-run EXPLAIN to confirm the plan changed.

Questions people ask

How do I read EXPLAIN ANALYZE output in Postgres?

Read the plan as a tree from the innermost, most indented nodes outward. For each node compare estimated rows with actual rows; a large gap means stale statistics. Multiply actual time by loops, because the docs report per-execution averages. The node with the biggest product is your bottleneck, and its type (Seq Scan, Sort, Hash, Nested Loop) tells you which fix to try.

Why is Postgres not using my index?

Three usual causes. The planner estimates a seq scan is cheaper, often because statistics are stale, so run ANALYZE on the table. The query wraps the column in a function or cast, such as LOWER(email) or id::text, which needs a matching expression index. Or the index's leading column is not in the WHERE clause, so a composite index on (a, b) cannot serve a filter on b alone.

Does Postgres automatically index foreign keys?

No. Postgres requires an index on the referenced primary or unique key, but the documentation states that declaring a foreign key does not create an index on the referencing columns. Without one, joins on that column and deletes or updates of parent rows can trigger sequential scans of the child table. Add the index yourself, using CREATE INDEX CONCURRENTLY on a live table.

Reading query plans takes a few hours to learn and pays back for years: "this is slow somehow" becomes "this step costs X and we fix it with Y."

Sources

Explore topics:Infrastructure
React
Share this post
Cite this article
Plain text

Kiril Urbonas (2026). Postgres Query Plans: Reading Them and the Indexes We Wish We'd Added Sooner. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/postgres-query-plans-and-indexes

Markdown

[Postgres Query Plans: Reading Them and the Indexes We Wish We'd Added Sooner](https://www.devopsness.com/blog/postgres-query-plans-and-indexes) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)

KU

Kiril Urbonas

Founder & Chief Editor

607 articles
View all articles by Kiril Urbonas

You might have missed

Evergreen posts worth revisiting.