EXPLAIN prints the plan the optimizer chose for a SELECT (and, since MySQL 8.0, for other statements) without running it — one row per table access, showing how each table is reached and roughly how many rows it touches. The two columns you read first are type, the access method, and Extra, which flags expensive work like sorting or building a temporary table. When type reads ALL, the server is scanning an entire table; that is almost always the query worth fixing. This guide decodes every column, walks a full-scan example into an indexed lookup, and uses EXPLAIN ANALYZE to confirm the change with real timings.
What you’ll accomplish
- Run
EXPLAINon a query and read each column:id,select_type,type,key,key_len,ref,rows,filtered, andExtra. - Rank
typevalues from best to worst and recognizeALLas a full table scan. - Turn a
type: ALLscan into atype: reflookup by adding the right index. - Read the dangerous
Extraflags:Using filesort,Using temporary, andUsing where. - Measure the real improvement with
EXPLAIN ANALYZEand inspect detail withFORMAT=JSON.
Prerequisites
- MySQL 8.0+ or MariaDB 10.6+.
EXPLAIN ANALYZErequires MySQL 8.0.18 or newer; MariaDB has hadANALYZEsince 10.1 with different output. - A sample table with enough rows that plans actually differ — a few hundred thousand at minimum. On a tiny table every access looks cheap and the exercise teaches you nothing.
- The
SELECTprivilege on the tables involved, plus whatever privileges the statement itself needs when you runEXPLAIN ANALYZE(it executes the query).
How it works
For every query, the optimizer estimates the cost of the access paths available — a full scan, each usable index, each join order — and picks the cheapest based on table statistics. EXPLAIN reports that decision. It does not run the query; the rows figure is an estimate drawn from the index statistics, not a measured count.
The single most useful column is type: the access method for each table. Its values form a ladder from best to worst. const and eq_ref mean the server reaches at most one row; ref and range mean an indexed lookup returning several rows; index means the whole index is scanned; ALL means every row of the table is read. Climbing a query up this ladder — usually from ALL to ref — is the core of query tuning.
The other columns give you the supporting detail: which index could be used (possible_keys), which one was chosen (key), how much of it was used (key_len), what it was compared against (ref), and what post-index work remained (Extra).
Step-by-step
Run plain EXPLAIN first to see the access path. Put EXPLAIN in front of the statement. Nothing executes, so it is safe even on a slow or expensive query.
EXPLAIN
SELECT id, total, customer_id
FROM orders
WHERE status = 'pending';
+----+-------------+--------+------+---------------+------+---------+------+---------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+--------+------+---------------+------+---------+------+---------+----------+-------------+
| 1 | SIMPLE | orders | ALL | NULL | NULL | NULL | NULL | 1998200 | 10.00 | Using where |
+----+-------------+--------+------+---------------+------+---------+------+---------+----------+-------------+
Decode the columns left to right. Each one answers a specific question:
id— the query block number. Higheridexecutes first; the sameidacross rows means those tables are joined in one block. Subqueries andUNIONparts get their ownid.select_type— the role of this block:SIMPLE(no subquery or union),PRIMARY(outermost of a compound query),SUBQUERY,DERIVED(a subquery in theFROMclause), orUNION.table— the table (or alias) this row is about.type— the access method.ALLhere means a full table scan.possible_keys— indexes the optimizer could have used.NULLmeans no index covers theWHEREclause; that is the root cause here.key— the index actually chosen.NULLconfirms no index is in play.key_len— how many bytes of the chosen index are used. On a composite index this tells you how many leftmost columns the query reached; a shorter-than-expectedkey_lenmeans the query stopped using the index partway.ref— what the index was compared against: a constant (const), or a column from another table in a join.rows— the optimizer’s estimate of rows examined for this table. Here ~2,000,000, the whole table.filtered— the estimated percentage of thoserowsthat survive theWHEREcondition.10.00means the server expects to read 2,000,000 rows and keep about 10%.Extra— additional work.Using wheremeans rows are filtered after being read; combined withtype: ALLit confirms a scan-then-filter.
Read the type-value ladder from best to worst. This is the ranking to memorize:
const— a primary-key or unique-index lookup against a constant. At most one row, effectively free.eq_ref— one row from this table for each row of the table joined before it, via a primary or unique key. The best you can hope for inside a join.ref— an indexed lookup on a non-unique key (or a prefix of a unique one), returning several matching rows per value. This is the target for most filtered queries.range— an index scan over a bounded range:BETWEEN,<,>,IN (...),LIKE 'abc%'. Usually acceptable.index— the entire index tree is scanned. Cheaper thanALLbecause the index is smaller than the table, but it still visits every entry.ALL— a full table scan. Every row is read, thenUsing wherethrows most away. The flag to hunt down on large tables.
Add an index on the filtered column and re-run. The predicate is status = 'pending', so a plain B-tree index on status gives the optimizer a ref path.
CREATE INDEX idx_orders_status ON orders (status);
EXPLAIN
SELECT id, total, customer_id
FROM orders
WHERE status = 'pending';
+----+-------------+--------+------+-------------------+-------------------+---------+-------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+--------+------+-------------------+-------------------+---------+-------+------+----------+-------------+
| 1 | SIMPLE | orders | ref | idx_orders_status | idx_orders_status | 42 | const | 4981 | 100.00 | Using where |
+----+-------------+--------+------+-------------------+-------------------+---------+-------+------+----------+-------------+
Three things changed. type went from ALL to ref; key is now idx_orders_status instead of NULL; and rows dropped from ~2,000,000 to 4,981 with filtered at 100%, because the index goes straight to the matching rows instead of scanning and discarding.
Get real timings with EXPLAIN ANALYZE. EXPLAIN estimates; EXPLAIN ANALYZE (MySQL 8.0.18+) runs the query and reports actual time and actual row counts per iterator, read bottom-up.
EXPLAIN ANALYZE
SELECT id, total, customer_id
FROM orders
WHERE status = 'pending';
-> Index lookup on orders using idx_orders_status (status='pending')
(cost=1120 rows=4981)
(actual time=0.041..7.930 rows=4981 loops=1)
cost and rows are the estimate; the actual time=0.041..7.930 block is real milliseconds (first-row .. last-row) and rows=4981 loops=1 is what actually came back. Before the index, the same query showed Table scan on orders (actual time=0.3..980 rows=1998200) — nearly a second reading two million rows. Comparing estimated rows against actual rows is the fastest way to catch bad statistics: a large gap means the optimizer is planning on wrong numbers.
Use FORMAT=JSON when you need every detail. The JSON format exposes fields the tabular output hides, such as used_key_parts, attached_condition, and per-operation cost.
EXPLAIN FORMAT=JSON
SELECT id, total, customer_id
FROM orders
WHERE status = 'pending';
{
"query_block": {
"table": {
"table_name": "orders",
"access_type": "ref",
"key": "idx_orders_status",
"used_key_parts": ["status"],
"rows_examined_per_scan": 4981,
"filtered": "100.00",
"attached_condition": "(orders.status = 'pending')"
}
}
}
Here access_type is the JSON name for the tabular type column. Reach for JSON when a composite index is only partly used and you need to see exactly which key parts the optimizer reached.
Validate it works
Confirm the fix on the plain EXPLAIN output, then measure it:
keyis populated. It names your index instead ofNULL.possible_keysshould list it too.typeimproved.ALLbecameref(orrange,eq_ref, orconst). Any of those means the index is doing the lookup.rowsdropped andfilteredrose. Fewer rows examined, and a higherfilteredpercentage means the index narrows the set before rows are read rather than after.- Actual time fell. Run
EXPLAIN ANALYZEand compare the top iterator’sactual timebefore and after. That is the honest number; thecostfigure is only a unit-less estimate.
Troubleshooting
-
The index exists but
keyis stillNULL. Usually a wrong column order in a composite index. An index on(a, b)cannot serve a query filtering only onb— the index is ordered byafirst. Put the equality-filtered column first, or add a dedicated index. Checkkey_lento see how far into a composite index the query actually reached. -
A function or cast around the column disables the index.
WHERE DATE(created_at) = '2026-07-25'orWHERE status = 42(comparing a string column to a number) forces a scan, because the index stores raw column values, not the result of a function or an implicit conversion. Rewrite as a range on the raw column (created_at >= '2026-07-25' AND created_at < '2026-07-26') or fix the literal’s type. On MySQL 8.0 a functional index (CREATE INDEX ... ((DATE(created_at)))) is another option. -
Using filesortin Extra. The server cannot satisfyORDER BYfrom an index and is sorting rows separately — in memory if they fit, otherwise on disk. Add an index whose column order matches theWHEREequality columns followed by theORDER BYcolumns, and the sort disappears. Despite the name,filesortdoes not always touch disk, but it is always extra work worth removing on hot queries. -
Using temporaryin Extra. The query needs an intermediate table, common withGROUP BYandDISTINCTover columns from different tables, orGROUP BYandORDER BYon different columns. Paired withUsing filesortit is a strong signal to redesign the indexes or the query. See Review MySQL indexes on a production database for choosing the composite index that removes both. -
Low
filteredwith a highrows. The optimizer expects to read many rows and keep few — a selective condition with no supporting index. This is the classic candidate for a new index. A lowfilteredthat persists after indexing points at stale statistics. -
Stale statistics make estimates wrong across the board. After a bulk load or a large delete, the index statistics lag reality and
EXPLAIN’srowsdiverges fromEXPLAIN ANALYZE’s actual rows, so the optimizer picks bad plans. Refresh them:ANALYZE TABLE orders;
When this is the wrong approach
EXPLAIN is an estimate, not a stopwatch. A plan that looks clean can still be slow if the statistics behind it are stale, so trust EXPLAIN ANALYZE’s actual time and the slow query log for real numbers before and after any change. Start from the slow query log to find which query costs the most; it is rarely the one you would guess, and tuning a query nobody runs is wasted effort.
Do not respond by indexing everything. Every index slows down INSERT, UPDATE, and DELETE, consumes disk, and adds a path the optimizer must consider. Add the specific index a real slow query needs, confirm it with EXPLAIN and EXPLAIN ANALYZE, and drop indexes that no query uses. Reading plans also cannot fix problems that only look like slow queries: an application issuing one query per row (N+1), lock contention under load, or a saturated connection pool all need fixes outside the plan. The authoritative reference is the MySQL manual on EXPLAIN output format and using EXPLAIN.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.