← Building blocks

Read the query plan

Latency & performancesenior

A query is slow and nobody knows whether it is the index, the join order or the row count.

Say it like this

Before adding hardware or a cache I read EXPLAIN ANALYZE for the slow query, because a sequential scan or a row estimate that is off by a thousand tells me exactly which index or statistic is missing.

Basic solution

Run EXPLAIN ANALYZE and read it bottom-up: look for sequential scans on big tables, nested loops over large sets, and estimated rows far from actual rows (stale statistics).

EXPLAIN ANALYZEpg_stat_statementsslow query logANALYZE to refresh stats

Reading a plan bottom-up

Start at the leaves. The sequential scan reads 250M rows to find 48, so the sort and everything above it inherits the cost. The composite index replaces both nodes with one index scan.

How it works

  1. Run EXPLAIN (ANALYZE, BUFFERS) on the exact query with parameters shaped like production data. ANALYZE actually executes the query and reports the real row counts and time spent at each step, not just the planner's estimates; BUFFERS adds how many pages came from cache versus disk.
  2. Read the output as a tree from the innermost node outward. The leaf nodes are scans that read data (Seq Scan reads the whole table, Index Scan walks an index then fetches rows, Index Only Scan answers from the index alone); the nodes above them are joins, sorts and aggregates that consume what the scans produce.
  3. On every node compare the estimated row count to the actual row count. A gap of 10x or more means the planner based its decisions on wrong statistics and will keep choosing bad join strategies until those statistics are fixed.
  4. Find where the time goes: a Seq Scan on a large table, a Nested Loop whose inner side ran thousands of times, a Sort that spilled to disk because the data did not fit in memory, or a Hash node that exceeded its memory budget (work_mem).
  5. Fix the cause rather than the symptom: add or reorder an index, run ANALYZE to refresh the statistics, rewrite the query so it does not wrap the indexed column in a function, or raise work_mem for that one session.
  6. Re-run EXPLAIN ANALYZE to confirm the plan changed and the time dropped, then move on to the next most expensive query in pg_stat_statements, the view that totals time per query.

What the common nodes mean

  • Seq Scan: reads every row of the table. Fine for small tables or when most rows match; a problem on a large table with a selective filter.
  • Index Scan: walks the index then fetches each matching row from the table. Index Only Scan skips the table fetch when the index already holds every column needed.
  • Nested Loop: for each row from the outer side, probe the inner side once. Cheap when the outer side is small; disastrous when it is not.
  • Hash Join and Merge Join: build a hash table or sort both sides once, then join in one pass. Suited to large sets.

Worked example

Notification status lookup

  • The API serves GET /v1/notifications/{id} and an ops dashboard runs "notifications for user X in the last day, newest first". The dashboard query takes 2.4 s on a 250 million row table.
  • EXPLAIN ANALYZE shows: Seq Scan on notification, rows estimated 1,200, actual 48; filter user_id = X AND created_at > now() - 1 day; then Sort by created_at desc. The scan reads 250M rows to return 48.
  • Cause: the only index is on created_at, and it cannot help here. The table keeps about a day of notifications (2,900 writes per second × 86,400 seconds ≈ 250M rows), so "the last day" matches nearly every row. The selective filter is user_id, and no index covers it, so the planner reads the whole table.
  • Fix: a composite index on (user_id, created_at desc). The plan becomes Index Scan with rows estimated 50, actual 48, no Sort node because the index order matches, and the query drops to about 1 ms. That is a 2,400x improvement for one index.
  • Second finding: estimated versus actual rows were off because statistics were last gathered before a backfill; ANALYZE notification corrected the estimates and the planner stopped choosing a Nested Loop on a related join.

Variants and when each wins

EXPLAIN without ANALYZE

  • Shows the plan the planner would choose and its estimates, without running the query. It wins as the first look at a query on production, because it is safe to run against anything, including writes.

EXPLAIN (ANALYZE, BUFFERS)

  • Executes the query and reports actual rows, time per node, and pages read from cache versus disk. It wins when you are diagnosing a specific slow query; wrap a write in a transaction you roll back.

Auto-explain and slow query logs

  • The database logs the plan of any query that runs longer than a threshold, automatically. It wins for catching the plans that only go bad at 3 am under production data, when nobody is watching.

pg_stat_statements and the MySQL performance schema

  • The database keeps a running total of time per normalised query. It wins for choosing what to fix first, because the biggest cost is often a fast query run millions of times rather than the single slowest one.

Recommendation: find candidates with pg_stat_statements, diagnose with EXPLAIN (ANALYZE, BUFFERS), and turn on auto-explain with a threshold so regressions surface on their own.

Failure modes

Plan flips under production data

  • You notice a query that was fast for months becomes slow after the table grows. It happens because the planner's estimates crossed a threshold and it switched from an index to a scan, or from a hash join to a nested loop. Fix it by re-checking statistics, adding the missing index, and alerting on that query's p99 so the next flip is caught early.

Stale statistics after a bulk load

  • You notice estimated rows are off by orders of magnitude right after a migration or backfill. It happens because the automatic statistics job has not run since the load, so the planner is reasoning about the table as it was. Fix it by running ANALYZE explicitly at the end of any bulk write.

Function on an indexed column

  • You notice an index exists but the plan shows a Seq Scan. It happens because the query filters on a function of the column (lower(email), created_at cast to a date), and the index holds raw values, not function results. Fix it by indexing the expression itself, or rewriting the predicate as a range on the raw column.

Sort spilling to disk

  • You notice a Sort node reports "external merge" and the query is slow even though the scan was fine. It happens because the rows being sorted did not fit in the memory budget (work_mem) and were written to temporary files. Fix it with an index that returns rows already in the required order, or by raising work_mem for that query.

Fast query, huge total cost

  • You notice the database is at 90 percent CPU but no single query is slow. It happens because a 2 ms query runs 20,000 times per second. Fix it by finding it in pg_stat_statements sorted by total time, then caching its result, batching its calls, or adding the index that makes it 0.1 ms.

Interviewer follow-ups

Answer out loud before you open each one.

What is the first thing you look for in a plan?

The biggest gap between estimated and actual rows, because that is where the planner is guessing wrong and every decision above that node inherits the error. After that, the node with the largest actual time, which is usually a scan or a nested loop fed by the bad estimate.

Why can a plan be fast in staging and slow in production?

The planner chooses based on table statistics, and a 10,000 row staging table makes every strategy cheap. Production has 250 million rows, different data distribution and different cache hit rates, so the same SQL gets a different plan. Test with production-sized data or a sampled copy.

When is a sequential scan the right plan?

When the filter matches a large fraction of the table, when the table is small enough to live in a few pages, or when the query needs most columns of most rows. Reading sequentially is cheaper per row than following an index into random pages, so the planner is right to pick it there.

How do you stop a bad plan from taking down production?

Statement timeouts so one query cannot hold resources for minutes, auto-explain to capture the plan when it happens, and a canary deploy for schema changes that could change plans. For a known bad plan, pin it with hints or an extension while the proper fix ships.

Connections

Built on
B-tree
Pairs with
Index the columns you filter on · Index selective columns first · Spread reads across replicas · Pool database connections