Skip to the fix
PHPSolvedThe fix first, then the reason

Newest fixes

Radovan Sykora in MySQL | | 7 min

MySQL EXPLAIN in practice: from a slow query to the right index

Put EXPLAIN in front of the query and read four columns: type, key, rows and Extra. They show whether an index is used, how well, and what is done after it.

A row of wooden drawers with one drawer open
On this page
  1. The four columns that matter
  2. EXPLAIN ANALYZE: plan and stopwatch
  3. Five queries that ignore a good index
  4. One index, several columns
  5. The answer inside the index
  6. Reading a join
  7. What EXPLAIN doesn't show
  8. An order of work

Write EXPLAIN in front of the slow SELECT and end it with \G to get one line per column. MySQL doesn't run the query. It answers with its plan:

sqlran on MySQL 8.0.33
CREATE TABLE orders (
  id INT AUTO_INCREMENT PRIMARY KEY,
  customer_id INT NOT NULL,
  status VARCHAR(10) NOT NULL,
  created DATE NOT NULL,
  total DECIMAL(8,2) NOT NULL,
  ref VARCHAR(12) NOT NULL
) STATS_SAMPLE_PAGES = 2000;

SET SESSION cte_max_recursion_depth = 20000;
INSERT INTO orders (customer_id, status, created, total, ref)
WITH RECURSIVE n (i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 20000)
SELECT 1 + CRC32(i) % 500,
       ELT(1 + CRC32(i * 7) % 10, 'new', 'sent', 'sent', 'sent', 'sent', 'sent', 'sent', 'sent', 'sent', 'void'),
       DATE('2024-01-01') + INTERVAL CRC32(i * 3) % 700 DAY,
       5 + CRC32(i * 11) % 20000 / 100,
       CONCAT(100000 + i)
FROM n;
ANALYZE TABLE orders;
sqlran on MySQL 8.0.33
EXPLAIN SELECT id, total FROM orders WHERE customer_id = 42\G
real output
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: orders
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 20000
     filtered: 10.00
        Extra: Using where

The table has 20,000 rows and no index apart from the primary key. type: ALL together with rows: 20000 is the sentence to learn: MySQL reads the whole table and checks every row. All plans on this page come from MySQL 8.0.33 and this table. The sample setting in the first line makes the estimates exact, so you should get the same numbers.

Now the index the query is asking for:

sqlran on MySQL 8.0.33
ALTER TABLE orders ADD INDEX by_customer (customer_id);
ANALYZE TABLE orders;
sqlran on MySQL 8.0.33
EXPLAIN SELECT id, total FROM orders WHERE customer_id = 42\G
real output
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: orders
   partitions: NULL
         type: ref
possible_keys: by_customer
          key: by_customer
      key_len: 4
          ref: const
         rows: 33
     filtered: 100.00
        Extra: NULL

From 20,000 rows to 33. That's the whole method, and the rest of the page is about reading the cases in between.

The four columns that matter

type is how the rows are found. The manual orders the values from best to worst. These are the ones you meet every day:

typeMeaning
constOne row through the primary key or a unique key
eq_refIn a join: one row per row of the table before
refAll rows with one value in an index
rangeA stretch of an index: >, <, BETWEEN, IN, LIKE 'abc%'
indexThe whole index, from one end to the other
ALLThe whole table

index sounds good and isn't. It reads every entry of an index. That's less to read than the table, and still everything.

key is the index that was chosen, NULL if none. possible_keys is the list it chose from. An empty list means that no index could help with the condition as it's written. A full list next to key: NULL means that MySQL thought reading the table was cheaper.

rows is an estimate of how many rows have to be looked at. Multiply it over the lines of a join to get a feeling for the total.

Extra is what happens besides. Three entries deserve attention: Using filesort (the rows are sorted after they were found), Using temporary (an intermediate table is built), and the good one, Using index (the answer came from the index alone).

filtered is the share of the looked-at rows that MySQL expects to survive the rest of the condition. Without statistics about a column it uses fixed guesses, such as the 10 percent in the first plan. The real share was 0.2 percent.

EXPLAIN ANALYZE: plan and stopwatch

EXPLAIN estimates. EXPLAIN ANALYZE runs the query and measures, so don't use it on a statement that takes an hour. It's available from MySQL 8.0.18 for SELECT:

sql
EXPLAIN ANALYZE SELECT id, total FROM orders WHERE customer_id = 42;
output
-> Index lookup on orders using by_customer (customer_id=42)
   (cost=11.6 rows=33) (actual time=0.0452..0.0473 rows=33 loops=1)

Two pairs of numbers: estimated rows and actual rows. When they differ by a factor of ten or more, the plan was made on wrong information, and ANALYZE TABLE is the first thing to try. MariaDB has the same idea under another name, ANALYZE SELECT, and its manual describes the output.

Five queries that ignore a good index

Add two more indexes and look at what defeats them:

sqlran on MySQL 8.0.33
ALTER TABLE orders ADD INDEX by_created (created), ADD INDEX by_ref (ref);
ANALYZE TABLE orders;
EXPLAIN SELECT COUNT(*) FROM orders WHERE YEAR(created) = 2025;
EXPLAIN SELECT COUNT(*) FROM orders WHERE created >= '2025-01-01' AND created < '2026-01-01';
EXPLAIN SELECT total FROM orders WHERE ref = 100042;
EXPLAIN SELECT total FROM orders WHERE ref = '100042';
EXPLAIN SELECT total FROM orders WHERE ref LIKE '%042';
EXPLAIN SELECT total FROM orders WHERE ref LIKE '1000%';

The essential columns of those six plans:

Conditiontypekeyrows
YEAR(created) = 2025indexby_created20000
created >= ... AND created < ...rangeby_created9552
ref = 100042ALLNULL20000
ref = '100042'refby_ref1
ref LIKE '%042'ALLNULL20000
ref LIKE '1000%'rangeby_ref99

A function around the column. The index holds dates and not years. Write the condition on the bare column, with a lower and an upper limit. The second row of the table reads half as many entries here, because half of the dates fall into that year. With one month in place of a year the gap is far wider.

A number compared with text. ref is a VARCHAR. Compared with a number, every row's text has to be converted first, since '100042', '0100042' and '100042.0' are all equal to the number. MySQL tells you in a warning after the EXPLAIN:

sqlran on MySQL 8.0.33
EXPLAIN SELECT total FROM orders WHERE ref = 100042;
SHOW WARNINGS LIMIT 1;
output
Cannot use ref access on index 'by_ref' due to type or collation conversion on field 'ref'

In PHP this happens when a value is bound as an integer or pasted without quotes. It returns the right row, so no test finds it.

A wildcard at the start. An index is sorted from the left, as a telephone book is. '%042' has no left end to start from. For searching inside text use a FULLTEXT index or a search engine.

Two ranges. One index can narrow the rows by a range on one column only. More about that in the next section.

A value that's too common. With an index on status, the plan for status = 'sent', which is four out of five rows, still shows ref with 10,000 estimated rows, exactly half of the table and far below the real number. An index that returns most of a table doesn't help. For a value that only ten percent of the rows have, 'new', the estimate was 1,995. An index on a column with three values is rarely worth its space on its own.

One index, several columns

"The last five orders of a customer" needs a condition and an order. With the index on customer_id alone the plan shows ref, 33 rows, and Using filesort. For 33 rows that's nothing. For a customer with 300,000 it's the whole wait. An index with both columns is already in the right order:

sqlran on MySQL 8.0.33
ALTER TABLE orders ADD INDEX by_customer_created (customer_id, created);
ANALYZE TABLE orders;
EXPLAIN SELECT id, total FROM orders WHERE customer_id = 42 ORDER BY created DESC LIMIT 5\G
output
possible_keys: by_customer,by_customer_created
          key: by_customer_created
         rows: 33
        Extra: Backward index scan

The sort is gone. "Backward index scan" means that the index is read from the end, because the query wants the newest first. The order of the columns follows a rule that covers most cases: first the columns compared with =, then the one that's sorted or compared with a range. After a range column, the remaining columns of the index can't narrow the search any further. The manual page on multiple-column indexes calls the usable part the leftmost prefix.

That prefix also makes the first index superfluous. by_customer_created starts with customer_id, so it can do everything by_customer can. An index you don't need costs time on every INSERT and space on disk. MySQL 8.0 lets you hide one before dropping it:

sqlran on MySQL 8.0.33
ALTER TABLE orders ALTER INDEX by_customer INVISIBLE;
EXPLAIN SELECT id FROM orders WHERE customer_id = 42\G
ALTER TABLE orders DROP INDEX by_customer;

If nothing gets slower for a week with the index invisible, the DROP is safe. Making it visible again takes a moment, building it anew may not.

The answer inside the index

If every column the query mentions is in the index, the table isn't read at all:

sqlran on MySQL 8.0.33
EXPLAIN SELECT customer_id, created FROM orders
WHERE customer_id = 42 AND created >= '2025-01-01'\G
output
         type: range
          key: by_customer_created
         rows: 17
        Extra: Using where; Using index

Using index is that case, usually called a covering index. It's the reason why SELECT * can be slow where three named columns are fast. Don't push every column into an index for it, though. Use it for the query that runs a hundred times a second.

InnoDB adds the primary key to every other index by itself, so id is always covered. The limits page has the maximum lengths, if you index long text.

Reading a join

A join has one line per table, and the order of the lines is the order of the work. The table at the top is the one MySQL starts with. For each of its rows the next table is searched, so the type on the second line matters most: eq_ref or ref is right, ALL on the second line multiplies. If a join is slow, check that both join columns have an index on the inner side and, above all, the same type and the same collation. An INT joined with a VARCHAR, or utf8mb4_0900_ai_ci with utf8mb4_unicode_ci, is the conversion problem from above in another place, and SHOW WARNINGS reports it there too.

What EXPLAIN doesn't show

A plan says nothing about waiting. A query that looks perfect can stand still because another transaction holds a lock, because the disk is busy, or because the pages it needs aren't in memory. If the same statement takes 5 milliseconds at night and 5 seconds at noon, the plan isn't the suspect.

It also says nothing about how often a query runs. A page that sends the same small SELECT four hundred times in a loop has four hundred good plans and is slow. Count the statements of one page before you tune the single one.

For a statement that's running right now, look it up with SHOW PROCESSLIST and ask for the plan of that connection: EXPLAIN FOR CONNECTION 57. The manual describes the form. It answers the question that a copy of the query in your console can't, namely what that session is doing with its own settings.

An order of work

  1. Find the query that costs most in total, not the one that looks worst. The slow query log counts for you.
  2. EXPLAIN it with the real values. A plan for customer 42 may differ from the one for your largest customer.
  3. Look for ALL or index with a large rows.
  4. Remove the function, the type conversion or the leading wildcard, if there is one.
  5. Add one index: equality columns first, then the range or sort column.
  6. EXPLAIN again, and measure with EXPLAIN ANALYZE.
  7. Drop the index it replaced.

Adding an index to a large table takes time and blocks some operations while it runs, so take a dump first and do it at a quiet hour. And if a query is killed rather than slow, with 2006 or 2013 in the PHP log, that's another page.

Same subject