Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 129/ 160
07. Indexing, Query Optimization & Performance Tuning

Reading & Interpreting EXPLAIN and EXPLAIN ANALYZE Output

Interpret plan trees, actual timing, and row estimates from EXPLAIN ANALYZE.

IntermediateEXPLAIN · ANALYZE · Plan3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

EXPLAIN shows the database's plan for your query; EXPLAIN ANALYZE runs it and shows what actually happened at each step.

Think of it like…

EXPLAIN is the GPS route estimate before you leave; EXPLAIN ANALYZE is driving the route with a stopwatch and noting exactly where you got stuck in traffic.

Where you’ve seen it

A dashboard query that took 200 ms last year now takes 9 seconds. EXPLAIN ANALYZE shows a Seq Scan reading 30 million rows to return 40 of them. An index on the filter column brings it back to a few milliseconds.

Words you’ll hear

Plan node
One step of the plan, such as Seq Scan, Index Scan, Hash Join, Sort or Aggregate.
cost
The planner's estimate in arbitrary units, shown as startup..total. Only useful for comparing plans of the same query.
actual time
Real milliseconds for the node (first row..last row), per loop.
loops
How many times the node ran. Multiply per-loop time and rows by it.

Visual diagram

Loading interactive diagram

Theory & example queries

Reading a plan tree

A plan is a tree. Each line is a node (Seq Scan, Index Scan, Hash Join, Sort…) and indented nodes feed rows into the node above them. Read it from the most-indented line outwards: the leaves read tables, the root returns rows to you.

Each node shows cost=startup..total, rows and width. Cost is in planner units, not milliseconds, and is only meaningful when comparing alternative plans for the same query. rows is how many rows the planner expects the node to output.

What a problem node looks like

Seq Scan on orders (cost=0.00..18334.00 rows=5 width=48) (actual time=0.02..142.70 rows=4980 loops=1): the planner expected 5 rows and got 4,980, and it read the whole table to find them. Both are worth fixing.

Key takeaway: Read innermost-first. Cost compares plans; actual time tells you where the time went.

What ANALYZE adds, and its traps

EXPLAIN ANALYZE runs the query and adds actual time=first..last (ms), actual rows and loops to each node. A node's time includes its children, and per-loop numbers must be multiplied by loops: a 0.05 ms Index Scan with loops=20000 costs a full second.

Add BUFFERS to see shared hit (pages found in cache) versus read (pages fetched from disk). A query that is slow the first time and fast the second is often a cold-cache problem, not a bad plan.

Measuring a write safelyQuery example
1Input dataStart from the source rows or state that the statement sees.
sessions
2 rows
sessions sample rows
iduser_idlast_seen_atactive
112026-11-21 09:00true
222026-11-20 18:30false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1BEGIN;23EXPLAIN4ANALYZE5DELETE FROM sessions6WHERE7  expires_at < now();89ROLLBACK;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
BEGIN Delete on sessions (actual rows=1200 loops=1) -> Seq Scan on sessions (actual rows=1200 loops=1) Planning Time: varies Execution Time: varies ROLLBACK

Note: Representative plan for 1,200 expired sessions only; row estimates, chosen plan, costs and timings vary with table size and statistics, while ROLLBACK discards the measured delete.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

measures the delete without keeping it.

Key takeaway: Multiply by loops, and never ANALYZE a write outside a transaction you roll back.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1You

Run EXPLAIN (ANALYZE, BUFFERS)

Run the slow query with EXPLAIN (ANALYZE, BUFFERS) on production-like data. A plan from a 100-row dev table tells you nothing about production.

SQL at this stepReadable preview
1EXPLAIN (ANALYZE,2  BUFFERS)3SELECT …
What to watch at this step
Runs the query
yes
Shows
plan + actuals
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

EXPLAIN shows the plan the database will use for a query: which tables it scans, which indexes it uses, the join order and method, and how many rows it expects at each step. EXPLAIN ANALYZE actually runs the query and adds the real time and real row counts for every step.

Why it matters: Most slow queries come down to one step in the plan: a full table scan, a nested loop over thousands of rows, or a sort spilling to disk. Reading the plan tells you which one, so you fix the actual cause instead of guessing which index to add.

When to reach for it

  • A query got slower after the table grew
  • You added an index and want to prove the planner uses it
  • An interviewer hands you a slow query and asks how you would investigate

When to avoid or be careful

  • Running EXPLAIN ANALYZE on writes in production without BEGIN … ROLLBACK
  • Comparing cost numbers across different queries; they are only comparable for the same query
  • Tuning on a small dev database whose statistics look nothing like production

EXPLAIN vs EXPLAIN ANALYZE vs pg_stat_statements

EXPLAIN
Best for: Checking which plan the database would choose

Strengths: Instant and safe: the query is not executed.

Watch out: Only estimates. It can't show where time is really spent.

EXPLAIN (ANALYZE, BUFFERS)
Best for: Diagnosing one slow query

Strengths: Real time, rows, loops and cache hits for every node.

Watch out: Runs the query: slow queries take just as long, and writes really happen.

pg_stat_statements
Best for: Finding which queries are slow in production

Strengths: Calls, total and mean time aggregated across every query.

Watch out: Tells you which query is slow, not why. You still need EXPLAIN ANALYZE.

Interview signals & numbers to know

When this topic comes up

  • “This query is slow. How would you debug it?”
  • “Why isn't my index being used?”
  • Seq Scan on a large table
  • Estimated rows far from actual rows
  • Rows Removed by Filter

Benchmarks & rules of thumb

≥10× -
estimate vs actual gap worth investigating
cost -
planner units, not milliseconds
loops -
multiply per-loop time by this
shared read -
pages fetched from disk, not cache

Common mistakes & follow-ups

Common interview mistakes

  • Running EXPLAIN ANALYZE on an UPDATE or DELETE in production: it really executes the statement. Wrap it in BEGIN … ROLLBACK.
  • Judging a plan by its total cost instead of finding the node with the biggest actual time.
  • Assuming every Seq Scan is bad. On small tables, or when a query returns most of the rows, a sequential scan is the fastest plan.

Likely interviewer follow-ups

  • The planner estimates 10 rows but the node returns 50,000. What causes that and how do you fix it?
  • Why might Postgres ignore an index on the column you filter by?
  • What does adding BUFFERS tell you that ANALYZE alone doesn't?
Interview tip: Answer in this order: run EXPLAIN (ANALYZE, BUFFERS) on production-like data, find the node with the largest actual time, compare its estimated vs actual rows, then fix the cause: an index, a query rewrite, or stale statistics.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Reading & Interpreting EXPLAIN and EXPLAIN ANALYZE Output with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Index Scan vs Index-Only Scan vs Bitmap Scan vs Sequential Scan
Next topic
Understanding Cost, Rows, Width, Buffers, Cache Hits & Disk Reads