Hard postgresql sql

How do you read an EXPLAIN ANALYZE plan, and what do you look for first?

The 30 second answer

A plan is a tree; rows flow from the leaves up. For each node I compare the estimated rows with the actual rows, multiply time by loops, and check Buffers for pages read from disk versus cache. A big gap between estimated and actual rows usually explains a bad join or scan choice. Then I look for sequential scans on large tables, rows removed by filter, sorts spilling to disk and nested loops with huge loop counts.

Could you say this in an interview?

From the basics. EXPLAIN shows the plan the planner chose, with estimates only. EXPLAIN ANALYZE actually runs the query and adds what really happened. BUFFERS adds how many 8 kB pages each node touched: shared hit from PostgreSQL's cache, read from the operating system or disk. In PostgreSQL 18, EXPLAIN ANALYZE includes BUFFERS automatically; in earlier versions you ask for it.

Because ANALYZE executes the statement, wrap an UPDATE or DELETE in a transaction you roll back.

How to read one node.

Nested Loop  (cost=4.65..118.50 rows=10 width=488) (actual time=0.017..0.051 rows=10.00 loops=1)
  Buffers: shared hit=36 read=6
  • cost=start..total: planner estimate in arbitrary units, not milliseconds.
  • rows=10 before actual: the estimate. rows=10.00 inside actual: what happened. PostgreSQL 18 prints actual rows with decimals; older versions print whole numbers.
  • loops: how many times the node ran. The docs: when a node runs more than once, "the actual time and rows values shown are averages per-execution… Multiply by the loops value to get the total time actually spent in the node."

What to check, in order.

  1. Estimated versus actual rows on each node. A planner that expects 1 row and gets tens of thousands will pick a nested loop or an index scan that's right for 1 row and terrible for the real number. That gap is the most common root cause; the statistics question below covers why it happens.
  2. The node with the most total time (time times loops), working up from the leaves.
  3. **Seq Scan on a big table with Rows Removed by Filter** in the hundreds of thousands: a missing or unusable index.
  4. **Sort Method: external merge Disk:**: the sort didn't fit in work_mem.
  5. **Buffers: read** much larger than hit: the working set isn't cached.

Example. A query for one customer's recent orders:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, status, created_at FROM orders
WHERE customer_id = 42 AND created_at >= now() - interval '30 days'
ORDER BY created_at DESC LIMIT 20;

If the plan shows a Seq Scan on orders with a Rows Removed by Filter close to the table size, the fix is an index on (customer_id, created_at); the next plan should show an Index Scan Backward with no separate sort.

Trade-offs.

  • EXPLAIN ANALYZE adds timing overhead, so the absolute time is a little higher than in production. Compare plans, not single runs.
  • Test on production-like data. The docs warn that small test tables lead to wrong conclusions, because a tiny table fits in one page and a sequential scan is cheapest.

Alternate interview scenarios

"The query is fast in staging and slow in production with the same indexes."

Different data size and distribution give different estimates and different plans. Run EXPLAIN (ANALYZE, BUFFERS) in production (on a replica if possible) and compare estimated and actual rows.

"A plan shows a Nested Loop whose inner index scan has a loops value in the tens of thousands."

The inner side ran once per outer row. If the outer estimate was 1 row, fix the estimate (statistics) or the query shape so the planner picks a hash join.

Sources (4)
  1. PostgreSQL docs: Using EXPLAINpostgresql.org
  2. PostgreSQL docs: EXPLAIN commandpostgresql.org
  3. PostgreSQL 18 release notes (BUFFERS included in EXPLAIN ANALYZE, fractional row counts)postgresql.org
  4. PostgreSQL docs: Examining index usagepostgresql.org