Skip to the fix
PHPSolvedThe fix first, then the reason

Newest fixes

Fixes for PHP, MySQL and the server around them

Paste the error, read the answer at the top of the page, then the reason. Code blocks that could be run were run, and each one says on which version.

Radovan Sykora in MySQL | | 7 min

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

A row of wooden drawers with one drawer open

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.

Read the whole fix

More fixes

Every fix, newest first

Short notes on the old addresses

By subject