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

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:
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;EXPLAIN SELECT id, total FROM orders WHERE customer_id = 42\G*************************** 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 whereThe 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:
ALTER TABLE orders ADD INDEX by_customer (customer_id);
ANALYZE TABLE orders;EXPLAIN SELECT id, total FROM orders WHERE customer_id = 42\G*************************** 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: NULLFrom 20,000 rows to 33. That's the whole method, and the rest of the page is about reading the cases in between.
PHPSolvedThe fix first, then the reason
PHPSettings, errors, types and functions, with the version each answer was run on.
MySQLErrors by number, dumps and restores, duplicates, indexes and slow queries.
phpMyAdminCookies, secrets, storage tables, imports and login screens that will not let you in.
nginx and ApacheServer blocks, PHP-FPM sockets, redirects, certificates and upload limits.
LinuxShell jobs around a web server: permissions, SSH, logs, archives, limits.
LaravelSubdirectories, keys, cookies, versions and deployment details.