01 / 21

EXPLAIN /
QUERY PLAN

Learn how databases think about your queries before executing them, and use that knowledge to write faster, smarter SQL.

SQL

What Is a Query Plan?

When you run a SQL query, the database does not just read your code top to bottom. Instead, a component called the query planner (or optimizer) first creates a step-by-step execution plan: which tables to scan, which indexes to use, and in what order to join data.

Why Should You Care?

★ Speed
A bad plan can make a query 1000x slower. EXPLAIN reveals the bottleneck.
★ Debugging
When a query is slow, EXPLAIN shows why: missing index, full table scan, bad join order.
★ Design
Understanding plans helps you design better schemas and indexes from the start.

The EXPLAIN Statement

To see the query plan, simply prepend EXPLAIN (or EXPLAIN QUERY PLAN in SQLite) before any SELECT, INSERT, UPDATE, or DELETE statement. The database returns the plan without actually executing the query.

-- MySQL / PostgreSQL EXPLAIN SELECT name, grade FROM students WHERE grade > 90; -- SQLite EXPLAIN QUERY PLAN SELECT name, grade FROM students WHERE grade > 90;

Anatomy of a Query Plan

SELECT FILTER (grade > 90) FULL TABLE SCAN INDEX SCAN Slow: reads every row Fast: uses index The plan is a tree: data flows UP from scans to the final result

Full Scan vs Index Scan

Full Table Scan Row 1: Alice, 85 Row 2: Bob, 92 ✓ Row 3: Carol, 78 Row 4: Dan, 95 ✓ Row 5: Eve, 60 Checks ALL 5 rows Index Scan Index on grade (sorted) 60 → Row 5 78 → Row 3 92 → Row 2 ✓ 95 → Row 4 ✓ Jumps to grade > 90 directly

Key Plan Operations

Seq Scan
Reads every row in the table. Slowest for large tables. Appears when no useful index exists.
Index Scan
Uses a B-tree index to jump directly to matching rows. Much faster for selective queries.
Sort
Reorders rows for ORDER BY. Expensive on large datasets without an index on the sort column.
Nested Loop
For each row in table A, scans table B. Good for small datasets or indexed lookups.
Hash Join
Builds a hash table of one table, then probes it with the other. Great for large unsorted joins.

Understanding Cost and Rows

Most EXPLAIN outputs include two critical numbers: the estimated cost (arbitrary units representing I/O and CPU work) and the estimated rows (how many rows the planner expects to process at each step).

Seq Scan on students (cost=0.00..35.50 rows=200 width=36) Filter: (grade > 90) Rows Removed by Filter: 800

EXPLAIN vs EXPLAIN ANALYZE

EXPLAIN EXPLAIN ANALYZE
Runs the query? No Yes
Shows estimated cost ✓ ✓
Shows actual time ✕ ✓
Shows actual row counts ✕ ✓
Safe on production ✓ Always Caution with writes

How to Read a Query Plan

1
Start at the deepest node. The innermost (most-indented) operations run first: they fetch raw data from tables or indexes.
2
Read upward. Each parent node processes output from its children: filtering, joining, sorting, or aggregating.
3
Look for Seq Scans. On large tables, a sequential scan often signals a missing index. This is usually the biggest performance win.
4
Compare cost and rows. High cost with many rows usually points to the most expensive step. Focus your optimization there.
5
Test your fix. Add an index, rewrite the query, then run EXPLAIN again to verify the plan improved.

Example 1: Simple WHERE

EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
Seq Scan on orders (cost=0.00..431.00 rows=5 width=64) Filter: (customer_id = 42)
CREATE INDEX idx_orders_customer ON orders(customer_id);
Index Scan using idx_orders_customer on orders (cost=0.29..8.31 rows=5 width=64) Index Cond: (customer_id = 42)

Example 2: JOIN Performance

EXPLAIN SELECT s.name, c.title FROM students s JOIN courses c ON s.course_id = c.id WHERE c.department = 'Math';
Hash Join (cost=12.50..85.30 rows=50) Hash Cond: (s.course_id = c.id) → Seq Scan on students (cost=0.00..65.00 rows=1000) → Hash → Index Scan on courses (cost=0.15..8.20 rows=10) Filter: (department = 'Math')

Example 3: ORDER BY + LIMIT

EXPLAIN SELECT name, score FROM leaderboard ORDER BY score DESC LIMIT 10;
Sort (cost=150.00..152.50 rows=1000) Sort Key: score DESC → Seq Scan on leaderboard (cost=0.00..50.00 rows=1000)
CREATE INDEX idx_leaderboard_score ON leaderboard(score DESC);
Limit (cost=0.29..1.05 rows=10) → Index Scan Backward using idx_leaderboard_score (cost=0.29..105.00 rows=1000)

Indexes: The Key to Fast Plans

B-Tree Index (simplified) 50 20 | 35 70 | 85 10, 15 25, 30 40, 45 55, 65 75, 80 90, 95 Finding grade = 85: only 3 comparisons (not 1000 rows) 50 → 70|85 → found at leaf

Common Mistakes

✕ Functions on Indexed Columns
Writing WHERE UPPER(name) = 'ALICE' prevents the index on name from being used. The index stores 'Alice', not 'ALICE'.
✕ SELECT * When Unnecessary
Selecting all columns forces the database to read full rows instead of using a covering index that has just the needed columns.
✕ Ignoring Row Estimates
If EXPLAIN says rows=1000 but you expect 5, your statistics are stale. Run ANALYZE to update them.

Query Plan Cheat Sheet

What You See What It Means What to Do
Seq Scan Full table scan Add an index
Index Scan Using index efficiently Good: no action
Sort (high cost) Sorting many rows Index on sort column
Nested Loop (large) Scanning inner table repeatedly Index the join column
Hash Join Building hash table for join Usually fine for large joins
rows estimate way off Stale statistics Run ANALYZE

Question 1 of 5

What does the EXPLAIN keyword do when placed before a SQL query?

Question 2 of 5

You see "Seq Scan on orders" in the query plan for a WHERE clause filtering by customer_id. What is the most likely issue?

Question 3 of 5

How does EXPLAIN ANALYZE differ from plain EXPLAIN?

Question 4 of 5

A query plan shows cost=0.00..431.00. What does the second number (431.00) represent?

Question 5 of 5

Why might writing WHERE UPPER(name) = 'ALICE' prevent the database from using an index on the name column?