SteelReed

Search

Search posts, questions…

4. Database & SQL

How SQL runs and how to read a PostgreSQL execution plan

How a query moves through the parser, planner and executor; the logical order of clauses; EXPLAIN ANALYZE and BUFFERS; scan types; reading cost, rows and loops; finding slow queries with pg_stat_statements.

18 Nov 20269 min readMid

–

The same correct query can take 0.5 ms or 900 ms depending on how the database decides to run it, and that decision lives in the execution plan. This post teaches you to read a PostgreSQL plan, find its most expensive node and pick the queries worth optimizing. Background reading: Indexes, EXPLAIN, N+1 and pagination (B+trees, covering, sargable predicates, MySQL's EXPLAIN); this series uses PostgreSQL 16.

1. The problem

After importing 3 million bookings, p95 of the "booking history" API goes from 40 ms to 2.5 seconds. Nobody deployed anything. The plan shows the planner guessed rows=1; reality was rows=48000.

2. Key idea

The planner lists ways to run the query, scores them by cost = unit cost × estimated rows, and picks the cheapest. Row counts come from statistics (pg_stats) written by ANALYZE or autovacuum. Wrong estimate, wrong choice.

Scan Use when Poor fit when Measured on the airline dataset
Seq Scan you need most of the table, small tables finding one row in a big table 1 ticket, no index: 30,000 pages, 98 ms
Index Scan few rows, index order needed big ranges: one random read per row same lookup: 4 pages, 0.5 ms
Index Only Scan the index has every column, table vacuumed write-heavy, not vacuumed: still reads the heap
Bitmap Heap Scan medium row counts, combining indexes you need index order 5,404 bookings in a day: 17 ms

2.1 How do you read a plan?

  • The most indented node runs first. Read inside out.
  • actual time=0.031..0.032 rows=1 loops=37 means 37 loops, about 1.2 ms and 37 rows in total.
  • An estimated rows off by more than 10× is the most important signal.
  • Filter with a large Rows Removed by Filter: wasted reads, a candidate for an index. Index Cond is the part that walks the index.
  • Large Heap Fetches on an Index Only Scan means missing VACUUM.

The logical order is FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT, so row filters go in WHERE, not HAVING.

3. In Java

JAVA
// Spring Data: findByEmailIgnoreCase(email)
// generated SQL: ... WHERE lower(u.email) = lower(?)
//
// EXPLAIN (ANALYZE, BUFFERS) on production-sized data:
//   Seq Scan on users (actual time=0.02..41.7 rows=1 loops=1)
//     Filter: (lower(email) = '[email protected]')
//     Rows Removed by Filter: 499999      -> the index on email can't be used
//
// Fix with a migration:
//   CREATE INDEX users_lower_email_idx ON users (lower(email));
//   Index Scan using users_lower_email_idx (actual time=0.03..0.03 rows=1)

Other languages: GORM, Prisma and SQLAlchemy can all print their SQL; plans read the same.

EXPLAIN ANALYZE on writes, and prepared statements

EXPLAIN ANALYZE DELETE ... really deletes. Wrap it in a transaction:

SQL
BEGIN;
EXPLAIN (ANALYZE, BUFFERS) DELETE FROM bookings WHERE book_date < '2017-01-01';
ROLLBACK;

A rollback still costs: locks while running, WAL and dead tuples. In production, use a copy.

Prepared statements: after 5 executions PostgreSQL may switch to a generic plan shared by all values. With skewed data (one status is 95% of the table), a fast query suddenly slows down. Check with PREPARE + EXPLAIN EXECUTE; fix with plan_cache_mode = force_custom_plan for the affected role.

4. Working with AI

Give the AI: reading long plans and naming the costliest node after multiplying by loops; writing index migrations; querying pg_stat_statements.

Check in AI-written code:

  • Conclusions come from EXPLAIN (ANALYZE, BUFFERS) on realistic data, not a 100-row table.
  • actual time was multiplied by loops before calling a node slow.
  • No EXPLAIN ANALYZE on writes outside BEGIN ... ROLLBACK.
  • Large import jobs end with ANALYZE table_name.

5. Exercises

Exercise 1: Read a plan

Nested Loop (actual time=5.0..49.0 rows=17 loops=3)
  -> Parallel Seq Scan on bookings b (actual time=4.9..48.5 rows=12 loops=3)
       Filter: (book_date >= '2017-03-01 10:00' AND book_date < '2017-03-01 10:10')
       Rows Removed by Filter: 700000
  -> Index Scan using tickets_book_ref_idx on tickets t (actual time=0.031..0.032 rows=1 loops=37)

The AI says "the Index Scan on tickets runs 37 times, so it's the culprit". Is that right? What do you fix?

Solution to Exercise 1

Wrong. The Index Scan on tickets totals about 0.032 × 37 ≈ 1.2 ms: fine. The culprit is the Parallel Seq Scan on bookings: each process discards 700,000 rows to find ~12, about 48.5 ms.

Fix: an index on bookings(book_date). The bookings side becomes an Index Scan of a few pages for ~37 rows, parallelism is no longer needed, and the total drops below 1 ms.

Exercise 2: Slow after an import

No deploy, only last night's 3-million-row import. The top query's mean_exec_time went from 3 ms to 1,800 ms. The plan shows rows=1 estimated, rows=48000 actual. The AI suggests SET enable_nestloop = off for the whole database. What do you do?

Solution to Exercise 2

Suspect stale statistics: check the table's pg_stat_user_tables.last_autoanalyze, dated before the import. Run ANALYZE tickets now (seconds, doesn't block writes) and recheck the plan.

Don't force plans database-wide: it changes every other query's plan and hides the problem. Root fix: add ANALYZE at the end of the import job; if the skew comes from the data (a '0000 000000' placeholder for passengers without documents), turn the placeholder into NULL.

Summary

  • The planner chooses by estimated rows; stale statistics give bad plans.
  • EXPLAIN (ANALYZE, BUFFERS) really runs; wrap writes in BEGIN ... ROLLBACK.
  • Multiply actual time by loops; rows off by more than 10× is the main clue.
  • Slow after an import: ANALYZE first, don't force plans.
  • Optimize the queries with the largest total time in pg_stat_statements.

Read more: PostgreSQL index lab.

Practice interview questions on this topic

All SQL & Query Tuning questions →

Loading comments…