Skip to the page

Performance · mid

Reading query plans with EXPLAIN

EXPLAIN shows the plan the database chose (scans, joins, sorts and their estimated costs), EXPLAIN ANALYZE actually runs the query and adds real row counts and timings, and comparing estimated with actual rows is how you find why a query is slow.

The notes

What you must know

  • Postgres scan types: Seq Scan (whole table), Index Scan (index then table), Index Only Scan (index alone), Bitmap Index/Heap Scan (many matching rows). Join types: Nested Loop, Hash Join, Merge Join.
  • EXPLAIN ANALYZE executes the statement: for INSERT/UPDATE/DELETE wrap it in BEGIN ... ROLLBACK. Add BUFFERS to see I/O.
  • Read from the innermost node out; look for the node with the largest actual time, and for estimated rows far from actual rows (stale statistics: run ANALYZE).
  • A Seq Scan is not always bad: for small tables or when most rows match, scanning is cheaper than using an index.
  • Find slow queries first: the pg_stat_statements extension (total time per query), slow query logs, APM traces, and ORM query logging.
  • Fix flow: confirm the plan -> add or change an index, or rewrite (avoid functions on columns, avoid SELECT *, paginate with keyset) -> EXPLAIN ANALYZE again -> check write cost.

The red pen

Common traps: mistake → fix

  • Mistake: EXPLAIN ANALYZE only shows the plan

    Fix: it runs the query, including writes.

  • Mistake: Seq Scan means a missing index

    Fix: for small tables or low selectivity the planner rightly prefers it.

Easy to hard

Questions interviewers ask, easy to hard

  1. A query takes 4 seconds. How do you find out why?
  2. EXPLAIN vs EXPLAIN ANALYZE?
  3. What do Seq Scan, Index Scan and Index Only Scan mean?
  4. The plan estimates 10 rows but gets 2 million. What does that tell you?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview