EXPLAIN /
QUERY PLAN
Learn how databases think about your queries before executing them, and use that knowledge to write faster, smarter 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?
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.
Anatomy of a Query Plan
Full Scan vs Index Scan
Key Plan Operations
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).
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
Example 1: Simple WHERE
Example 2: JOIN Performance
Example 3: ORDER BY + LIMIT
Indexes: The Key to Fast Plans
Common Mistakes
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?