The Innocent-Looking SQL Query
You’re working for an online shopping company. It’s been a busy week, and you’re just settling in when someone from the support team drops a message:
“Hey, users are saying their order history page is super slow. Can you take a look?”
So you open up the backend code and there it is — a simple query:
SELECT * FROM orders WHERE customer_id = 1234;
It looks clean and straightforward. It should be fast. But it’s not.
Why Use EXPLAIN?
You’re not about to start guessing. You want to know exactly how the database is handling this query. That’s where EXPLAIN
comes in.
It’s a tool that tells the database: “Don’t run this query — just show me your plan for it.”
You type:
EXPLAIN SELECT * FROM orders WHERE customer_id = 1234;
Understanding the Execution Plan Output
The database responds with something like this:
id | select_type | table | type | key | rows | Extra |
---|---|---|---|---|---|---|
1 | SIMPLE | orders | ALL | NULL | 1,000,000 | Using where |
This means:
type = ALL
: A full table scan — slow.key = NULL
: No index is being used.rows = 1,000,000
: It will check every row.
Even though the query looks efficient, the execution plan shows it’s very expensive.
Optimizing with an Index
You realize there’s no index on customer_id
, so you add one:
CREATE INDEX idx_customer_id ON orders(customer_id);
Now, you run EXPLAIN
again:
EXPLAIN SELECT * FROM orders WHERE customer_id = 1234;
The output now looks like this:
id | select_type | table | type | key | rows | Extra |
---|---|---|---|---|---|---|
1 | SIMPLE | orders | ref | idx_customer_id | 5 | Using where |
Much better — the query is now using the index, scanning only a few rows, and runs fast.
Breakdown of the Syntax and Output
Let’s look at the syntax again:
EXPLAIN SELECT * FROM orders WHERE customer_id = 1234;
Explanation:
- EXPLAIN: Ask for the execution plan.
- SELECT *: Retrieve all columns.
- FROM orders: From the orders table.
- WHERE customer_id = 1234: Filter by customer.
Output fields:
- type: Access type (ref is good, ALL is bad).
- key: The index used, if any.
- rows: Estimated rows scanned.
Why EXPLAIN Is So Useful in Real Life
With one simple command, you can:
- Find slow queries before they hit production.
- Understand how your database is thinking.
- Decide where indexes are needed.
- Measure the impact of your optimizations.
Final Thought
Next time a query is slow or a page loads like molasses, don’t guess — use EXPLAIN
. It’s like debugging with x-ray vision.
Want to explore joins next? Or break down an actual query you’re using? Let’s keep going.