The EXPLAIN statement provides a look under the hood of how MySQL executes your SQL queries. It is the primary diagnostic tool for understanding performance, revealing whether the database is using indexes effectively or performing slow full-table scans.
Prepend the keyword EXPLAIN to your query. MySQL will process the statement and return details about the execution plan instead of the result set.
-- Standard syntax for analyzing a SELECT statement
EXPLAIN SELECT * FROM users WHERE email = 'jdoe@example.com';
-- FORMAT=JSON gives more detailed, machine-readable output
EXPLAIN FORMAT=JSON SELECT * FROM orders WHERE id = 105;
Below is an example comparing a query that uses an index versus one that might trigger a table scan.
-- Scenario: We want to find employees in a specific department
-- Case 1: If 'department_id' is indexed, this is fast (ref)
EXPLAIN SELECT name, role FROM employees WHERE department_id = 5;
-- Case 2: If searching by a non-indexed column like 'bio', this is slow (ALL)
EXPLAIN SELECT name FROM employees WHERE bio LIKE '%developer%';
When you run EXPLAIN, you receive a result table like this:
| id | select_type | table | type | key | rows |
|---|---|---|---|---|---|
| 1 | SIMPLE | employees | ref | idx_dept | 12 |
Crucial Columns to Watch:
type: The join type.
key: The actual index MySQL decided to use. If NULL, no index was used.rows: Estimate of how many rows MySQL must examine to find the result. Lower is better.ref, range, or const. If you see ALL on a large table, you likely need an index.key column.WHERE clause matches your composite index (Leftmost Prefix Rule).WHERE column = 'value' and check the type.CREATE INDEX idx_name ON table(column);EXPLAIN again and observe how the type changes from ALL to ref and rows decreases drastically.