As a Senior SQL Master, you don't just "hope" your query is fast. You prove it. The EXPLAIN command allows you to look inside the MySQL Brain and see exactly how it intends to find your data.
EXPLAIN: A keyword you put before your SELECT statement. Instead of running the query, MySQL returns a table describing the "Execution Plan"—which indexes it will use, and how many rows it expects to read.
- Debugging Slowness: Finding out why a query that should take 1ms is taking 5 seconds.
- Index Verification: Confirming that MySQL is actually using the index you created.
- Optimization: Comparing two different ways of writing the same query to see which is more efficient.
| Column | What to look for |
|---|---|
type |
const or ref is good. ALL is terrible (Full Table Scan). |
possible_keys |
The indexes MySQL could use. |
key |
The index MySQL actually selected. If this is NULL, you have no index! |
rows |
The estimated number of rows MySQL must examine. Lower is better. |
Extra |
Using index means it's a Covering Index (Fastest!). Using filesort is very slow. |
-- Just put EXPLAIN at the start
EXPLAIN SELECT * FROM Users WHERE Email = '[email protected]';
-- In MySQL 8.0, use ANALYZE for the actual real-time execution stats
EXPLAIN ANALYZE SELECT * FROM Users WHERE Email = '[email protected]';- Look at the
typecolumn first. If you seeALL, add an index. - Look at the
rows. If it's close to the total number of rows in the table, your filter isn't working well. - Look at
Extra. If you seeUsing filesort, yourORDER BYis slow. Try adding an index to the sorting column.
The Missing Index Catch:
Query: SELECT * FROM Orders WHERE status = 'shipped' ORDER BY order_date;
EXPLAINshowstype: ALLandExtra: Using filesort.- The Fix: Create a composite index on
(status, order_date). - Result:
EXPLAINnow showstype: refandExtra: Using index.
- Task 1: What does
type: ALLin anEXPLAINplan indicate? - Task 2: Which
EXPLAINcolumn tells you which index MySQL actually decided to use for the query?