Skip to the content

Lesson 221 of 296

EXPLAIN and the N+1 problem

What you will learn

  • What a query planner is
  • Reading EXPLAIN output
  • EXPLAIN ANALYZE
  • Common plan nodes and what they tell you
  • A method for fixing a slow query
  • The N+1 query problem and how to fix it
On this page

The query planner

SQL is declarative: you say what you want, not how to get it. The database's query planner (optimiser) chooses the how: which index to use, in which order to join tables, which join method, whether to sort. It estimates the cost of possible plans using statistics about your data (row counts, value distribution) and picks the cheapest.

EXPLAIN

EXPLAIN shows the plan without running the query:

EXPLAIN SELECT * FROM events WHERE user_id = 42 ORDER BY created_at DESC LIMIT 10;

Limit  (cost=146.18..146.21 rows=10 width=26)
  ->  Sort  (cost=146.18..146.28 rows=40 width=26)
        Sort Key: created_at DESC
        ->  Bitmap Heap Scan on events  (cost=4.60..145.32 rows=40 width=26)
              Recheck Cond: (user_id = 42)
              ->  Bitmap Index Scan on events_user_id_idx  (cost=0.00..4.59 rows=40 width=0)
                    Index Cond: (user_id = 42)

How to read it:

  • It is a tree. Read from the innermost (most indented) line outwards: the index is scanned first, then the table rows are fetched, then sorted, then limited.
  • cost=4.60..145.32: estimated start-up cost (before the first row) and total cost, in arbitrary units. Compare costs between plans; they are not milliseconds.
  • rows=40: the estimated number of rows.
  • width=26: estimated average row size in bytes.

EXPLAIN ANALYZE

EXPLAIN ANALYZE actually runs the query and shows real numbers next to the estimates:

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) SELECT * FROM events WHERE user_id = 42 ORDER BY created_at DESC LIMIT 10;

Limit (actual rows=10.00 loops=1)
  Buffers: shared hit=20 read=3 dirtied=1 written=1
  ->  Index Scan using events_user_created_idx on events (actual rows=10.00 loops=1)
        Index Cond: (user_id = 42)
        Index Searches: 1
        Buffers: shared hit=20 read=3 dirtied=1 written=1
Planning Time: 0.048 ms
Execution Time: 0.351 ms

(Run against the 200,000-row test table from Lesson 220 after adding the composite index. Recent PostgreSQL versions include buffer counts automatically.)

  • actual rows: how many rows each step really produced. If estimates and actual rows differ hugely (estimated 10, actual 500,000), statistics are stale or misleading, and the planner may have chosen a bad plan; run ANALYZE.
  • Buffers: pages read from memory (hit) or from disk (read). Fewer is better.
  • Execution Time: the real time.
  • Careful: EXPLAIN ANALYZE on an UPDATE or DELETE really changes data. Wrap it in BEGIN; ... ROLLBACK;.

Plan nodes to recognise

NodeMeaningUsually
Seq ScanReads the whole tableFine for small tables or when many rows match; a warning sign on big tables with selective filters
Index ScanWalks the index, fetches matching rowsGood for few rows
Index Only ScanAnswers from the index aloneBest (Lesson 220)
Bitmap Index / Heap ScanCollects matching row locations, then reads them in disk orderGood for a medium number of rows
Nested LoopFor each row on one side, look up matches on the otherGood when one side is small and the other has an index
Hash JoinBuilds a hash table of one side, probes it with the otherGood for large joins without useful indexes
Merge JoinJoins two inputs already sorted on the keyGood for large sorted inputs
SortSorts rows; "external merge Disk" means it spilled to diskCan often be removed with an index in the right order
Hash Aggregate / Group AggregateGROUP BY

A method for a slow query

  1. Find the slow query: application logs, an APM tool, or PostgreSQL's pg_stat_statements extension (shows total time per query pattern).
  2. Run EXPLAIN (ANALYZE, BUFFERS) on it with realistic parameters.
  3. Find the most expensive step: a Seq Scan on a big table, a big Sort, a huge difference between estimated and actual rows, a Nested Loop running thousands of times.
  4. Fix: add or change an index (Lesson 220), rewrite the query (avoid functions on indexed columns, select fewer columns, filter earlier), update statistics, paginate with keysets (Lesson 222), or cache the result (Lesson 205).
  5. Measure again. Check the fix does not slow down writes too much.

The N+1 problem

A very common performance bug, especially with ORMs (Lesson 230). You load a list (1 query), then for each item load something related (N more queries):

const orders = await db.query("SELECT * FROM orders");                 1 query
for (const order of orders) {
  order.customer = await db.query("SELECT * FROM customers WHERE id = $1", [order.customer_id]);   N queries
}

For 100 orders that is 101 round trips to the database. Each one may take only a millisecond, but network latency adds up, and under load it hammers the database. It is called N+1 because of the 1 + N queries.

The fix: fetch related data in one go:

  • A JOIN: SELECT o.*, c.name FROM orders o JOIN customers c ON c.id = o.customer_id.
  • Or batch the lookups: one query for the orders, then one query WHERE id = ANY($1) with all the customer IDs, and match them up in code.
TypeScript
type OrderRow = { id: number; customer_id: number; status: string };
type CustomerRow = { id: number; name: string };
type Db = { query<T>(sql: string, params?: unknown[]): Promise<{ rows: T[] }> };

export async function ordersWithCustomers(db: Db) {
  const { rows: orders } = await db.query<OrderRow>("SELECT id, customer_id, status FROM orders ORDER BY id");
  const ids = [...new Set(orders.map((o) => o.customer_id))];
  const { rows: customers } = await db.query<CustomerRow>("SELECT id, name FROM customers WHERE id = ANY($1)", [ids]);
  const byId = new Map(customers.map((c) => [c.id, c]));
  return orders.map((o) => ({ ...o, customerName: byId.get(o.customer_id)?.name ?? null }));
}

Two queries, however many orders there are. ORMs do this for you when you ask them to eager load relations (Prisma include, Lesson 230). In GraphQL, the DataLoader pattern batches lookups the same way.

Spotting N+1: log the number of queries per request; many near-identical queries in a row is the signature. APM tools flag it automatically.

How to say it in an interview

"The planner chooses how to run a query based on statistics, and EXPLAIN shows that plan as a tree with estimated costs and rows, while EXPLAIN ANALYZE runs it and shows actual rows, buffers and time. I look for sequential scans on big tables, expensive sorts, nested loops running many times, and big gaps between estimated and actual rows, then fix with indexes, query rewrites, fresh statistics or caching, and measure again. N+1 is loading a list with one query and then one query per item; I fix it with a join or a single batched WHERE id = ANY query, or eager loading in the ORM, and I watch query counts per request."

Key words

WordMeaning
Query plannerChooses how to execute a query
EXPLAINShows the plan without running it
EXPLAIN ANALYZERuns the query and shows actual statistics
CostThe planner's estimate of work, in arbitrary units
Seq Scan / Index ScanRead the whole table / use an index
Nested Loop / Hash Join / Merge JoinWays of joining tables
N+1 problemOne query for a list plus one per item
Eager loadingLoading related data up front in few queries

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.