Databases · Intermediate · 20 min
Read MySQL 9.7 query plans and add the right index
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · MySQL 9.7.4 LTS (InnoDB)
You will load 500,000 orders into MySQL 9.7, read the plans for a slow query with EXPLAIN and EXPLAIN ANALYZE, and replace a full table scan with a composite, covering index, then retire a redundant index safely and switch on the slow query log.
On this page
Most slow MySQL queries have the same cause: the server reads far more rows than it returns. MySQL will show you how it plans to run a query and, with EXPLAIN ANALYZE, how it actually ran. Once you can read those plans, choosing an index stops being guesswork.
In this tutorial you build an orders table with 500,000 rows and take one slow query, "a customer's recent orders, newest first", from a full table scan to an index range scan that reads a few dozen rows. Along the way you meet the leftmost-prefix rule, covering indexes, the function trap, invisible indexes and the slow query log. The engine is InnoDB, the default, and the notes point out where it behaves differently from PostgreSQL.
You need MySQL 9.7 LTS installed as in /tutorials/install-mysql-9-7-lts-on-ubuntu-26-04, where the database root account signs in through sudo mysql. The plans shown were produced by MySQL 9.7. Your cost and row estimates will differ a little, but the plan shapes will match.
Step 1 · Load 500,000 orders
Create a database called shop and an orders table, then fill it from a recursive common table expression. The values follow fixed patterns rather than random numbers, so you get the same data, and the same counts, every time: 2,000 customers with exactly 250 orders each, spread across 2026.
MySQL stops a recursive CTE after 1,000 rounds by default, so the script raises cte_max_recursion_depth for this session only.
sudo mysql <<'SQL'
CREATE DATABASE shop CHARACTER SET utf8mb4;
USE shop;
CREATE TABLE orders (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
customer_id INT UNSIGNED NOT NULL,
status VARCHAR(10) NOT NULL,
created_at DATETIME NOT NULL,
total_cents INT UNSIGNED NOT NULL
);
SET SESSION cte_max_recursion_depth = 500000;
INSERT INTO orders (customer_id, status, created_at, total_cents)
WITH RECURSIVE seq (n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM seq WHERE n < 500000
)
SELECT 1 + (n * 7919) % 2000,
ELT(1 + n % 4, 'new', 'paid', 'shipped', 'refunded'),
'2026-01-01' + INTERVAL (n * 37) % 525600 MINUTE,
500 + (n * 131) % 20000
FROM seq;
ANALYZE TABLE orders;
SQLThe insert takes several seconds. ANALYZE TABLE refreshes the statistics the optimiser uses to estimate how many rows each step returns. InnoDB updates them on its own after enough rows change, but running it after a bulk load means your first plans are built on accurate numbers.
Check it worked
sudo mysql shop -e "SELECT COUNT(*) AS orders, COUNT(DISTINCT customer_id) AS customers FROM orders;"The output shows 500000 orders and 2000 customers.
Step 2 · Read the plan with EXPLAIN
This is the query the shop's account page runs, and it is slow:
SELECT id, created_at, total_cents
FROM orders
WHERE customer_id = 1234 AND created_at >= '2026-10-01'
ORDER BY created_at DESC;Put EXPLAIN in front of it to see the plan without running it. MySQL 9.7 prints plans as a tree by default (explain_format is TREE), so ask for the traditional field list with FORMAT=TRADITIONAL. The -E (--vertical) option prints one field per line, which is easier to read than a wide table:
sudo mysql shop -E -e "EXPLAIN FORMAT=TRADITIONAL SELECT id, created_at, total_cents FROM orders WHERE customer_id = 1234 AND created_at >= '2026-10-01' ORDER BY created_at DESC"You see something like this:
id: 1
select_type: SIMPLE
table: orders
partitions: NULL
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 498744
filtered: 3.33
Extra: Using where; Using filesortFour fields tell you most of the story:
typeis how MySQL reaches the rows.ALLmeans it reads every row in the table. You will meet better values shortly:ref(look up rows by one value in an index) andrange(read a slice of an index).keyis the index it chose.NULLmeans none, andpossible_keys: NULLsays there was nothing to choose from.rowsis the estimate of rows examined, here roughly the whole table.filteredis the estimated percentage that survive theWHERE.Extra: Using filesortmeans MySQL must sort the results itself after finding them.
Now look at the same plan as a tree. It shows the order the work happens in, innermost first. Expect something like the output below it:
sudo mysql shop -E -e "EXPLAIN FORMAT=TREE SELECT id, created_at, total_cents FROM orders WHERE customer_id = 1234 AND created_at >= '2026-10-01' ORDER BY created_at DESC"-> Sort: orders.created_at DESC (cost=50498 rows=498744)
-> Filter: ((orders.customer_id = 1234) and (orders.created_at >= TIMESTAMP'2026-10-01 00:00:00')) (cost=50498 rows=16623)
-> Table scan on orders (cost=50498 rows=498744)Read it from the bottom up: scan the whole table, filter, then sort. The cost numbers are the optimiser's internal units, useful for comparing plans of the same query, not milliseconds.
Check it worked
Your traditional plan shows type: ALL and key: NULL, and the tree has a Table scan on orders line at the bottom.
Step 3 · Measure it with EXPLAIN ANALYZE
EXPLAIN ANALYZE runs the query and reports what each step really did. By default its output is a tree. It has no traditional table format:
sudo mysql shop -E -e "EXPLAIN ANALYZE SELECT id, created_at, total_cents FROM orders WHERE customer_id = 1234 AND created_at >= '2026-10-01' ORDER BY created_at DESC"The output looks something like this, with your own timings:
-> Sort: orders.created_at DESC (cost=50498 rows=498744) (actual time=181..181 rows=63 loops=1)
-> Filter: ((orders.customer_id = 1234) and (orders.created_at >= TIMESTAMP'2026-10-01 00:00:00')) (cost=50498 rows=16623) (actual time=2.1..181 rows=63 loops=1)
-> Table scan on orders (cost=50498 rows=498744) (actual time=0.06..152 rows=500000 loops=1)Each line now has a second bracket:
actual time=0.06..152is milliseconds to the first row and to the last row.rows=500000on the scan againstrows=63from the filter is the problem in one line: half a million rows read to return 63.loops=1is how many times the step ran. In a join, the inner side can run thousands of times, and its time and rows are per loop.
Compare the estimated rows with the actual ones too. When they differ by ten times or more, run ANALYZE TABLE and look again, because a plan built on a bad estimate is often a bad plan.
EXPLAIN ANALYZEreally executes the statement. On aSELECTthat is harmless. MySQL also accepts it in front of multi-tableUPDATEandDELETEstatements, and those change your data, so run them insideSTART TRANSACTION; ... ROLLBACK;if you need their plans.
Check it worked
Your output has actual time= on every line, and the Table scan on orders line reports rows=500000. Note the last-row time on the top line; you will compare against it after each index.
Step 4 · Add an index and see ref
The query filters on customer_id, so start with an index on that column:
sudo mysql shop -e "CREATE INDEX orders_customer_idx ON orders (customer_id);"
sudo mysql shop -E -e "EXPLAIN FORMAT=TRADITIONAL SELECT id, created_at, total_cents FROM orders WHERE customer_id = 1234 AND created_at >= '2026-10-01' ORDER BY created_at DESC"On a busy table, InnoDB builds a secondary index online by default: reads and writes carry on while it runs, though it takes time and extra disk on a large table.
The plan now shows something like type: ref, key: orders_customer_idx, ref: const and rows: 250. MySQL looks up the 250 rows for customer 1234 in the index and fetches each one from the table. Extra still contains Using filesort and Using where: it checks the date on all 250 rows and sorts the survivors.
This is where InnoDB differs from PostgreSQL. An InnoDB table is stored as a B-tree ordered by its primary key, the clustered index, and the full rows live in its leaves. A secondary index such as orders_customer_idx stores the indexed column plus the primary key value, not a pointer to a disk location. Every row it finds costs a second lookup in the primary key tree. PostgreSQL keeps rows in an unordered heap, and every index points straight at a heap location. Two practical rules follow for MySQL: keep primary keys short, because every secondary index carries a copy, and prefer an auto-increment or otherwise ascending key, so new rows go at the end of the tree.
Check it worked
Your plan shows type: ref and key: orders_customer_idx. Run the EXPLAIN ANALYZE from the previous step again: the scan line is replaced by an Index lookup on orders using orders_customer_idx line reading 250 rows, and the time drops from around a couple of hundred milliseconds to about a millisecond.
Step 5 · Build a composite index and get a range scan
A composite index sorts by its first column, then by the second within each value of the first. An index on (customer_id, created_at) holds each customer's orders already in date order, so MySQL can jump to customer 1234, start at 1 October and read only the matching entries, in the order the query wants:
sudo mysql shop -e "CREATE INDEX orders_customer_created_idx ON orders (customer_id, created_at);"
sudo mysql shop -E -e "EXPLAIN FORMAT=TRADITIONAL SELECT id, created_at, total_cents FROM orders WHERE customer_id = 1234 AND created_at >= '2026-10-01' ORDER BY created_at DESC"The plan shows something like type: range, key: orders_customer_created_idx, rows: 63 and an Extra that includes Backward index scan. possible_keys lists both indexes, and the optimiser picked the one that examines fewer rows. Using filesort has gone: reading the index backwards gives newest-first for free, and the date condition is applied inside the index, so only the 63 matching rows are fetched from the table.
Column order matters, because of the leftmost-prefix rule. MySQL can use an index for a condition on its first column, on its first two, and so on, but not for a condition that skips the first column. Try a query on the date alone:
sudo mysql shop -E -e "EXPLAIN FORMAT=TRADITIONAL SELECT * FROM orders WHERE created_at >= '2026-12-30'"The plan is back to type: ALL with key: NULL. The dates are sorted within each customer, but across the whole index they are scattered, so the index cannot find them. For a query the index fully covers, MySQL can sometimes use a skip scan instead, but do not design around it. The rule of thumb: put the columns you test with = first, then the one you test with a range or sort on.
Check it worked
The main query's plan shows type: range and key: orders_customer_created_idx, with no Using filesort. The date-only query shows type: ALL.
Step 6 · Make the index cover the query
Each of the 63 rows still costs a trip to the clustered index to fetch the columns the index does not hold. If the index holds every column the query needs, MySQL skips that trip. This is a covering index, and EXPLAIN marks it with Using index in Extra.
Because InnoDB secondary indexes already carry the primary key, orders_customer_created_idx contains customer_id, created_at and id. A query that asks only for those is covered already:
sudo mysql shop -E -e "EXPLAIN FORMAT=TRADITIONAL SELECT id, created_at FROM orders WHERE customer_id = 1234 AND created_at >= '2026-10-01' ORDER BY created_at DESC"Extra now reads something like Using where; Backward index scan; Using index. Compare it with the earlier query, which also asked for total_cents: its Extra has no Using index, because each row still had to be fetched from the table. Watch for Using index condition in other plans: despite the name, it means a condition was checked in the index and the rows were still fetched.
To cover the full account-page query, add total_cents to the end of the index. Adding it at the end keeps the leftmost prefix intact, so the index still serves every query the two-column one did. Weigh that against the cost: every extra column makes the index bigger and every insert slower. Cover the queries that run constantly, not every query.
In PostgreSQL you would get the same effect with INCLUDE (total_cents), and an index-only scan there also depends on the table's visibility map being up to date. InnoDB has no INCLUDE clause and no visibility map; a covering index is just one with the right columns.
Check it worked
Your plan for the id, created_at query shows Using index in Extra, and the plan for the query that also selects total_cents does not.
Step 7 · Stop a function from hiding the column
The finance team runs a daily report with a natural-looking condition. Give created_at an index of its own and look at the plan:
sudo mysql shop -e "CREATE INDEX orders_created_idx ON orders (created_at);"
sudo mysql shop -E -e "EXPLAIN FORMAT=TRADITIONAL SELECT COUNT(*), SUM(total_cents) FROM orders WHERE DATE(created_at) = '2026-03-14'"The plan shows type: ALL even though an index on created_at exists. The index is sorted by created_at, but the query asks about DATE(created_at), a different value MySQL would have to compute for every row before it could compare. Any function, cast or arithmetic wrapped around a column has the same effect.
The best fix is usually to rewrite the condition as a range on the bare column:
sudo mysql shop -E -e "EXPLAIN FORMAT=TRADITIONAL SELECT COUNT(*), SUM(total_cents) FROM orders WHERE created_at >= '2026-03-14' AND created_at < '2026-03-15'"That plan uses orders_created_idx with type: range. When you cannot change the query, for example in a reporting tool that generates its SQL, MySQL can index the expression itself. Note the double brackets, which mark a functional key part:
sudo mysql shop -e "CREATE INDEX orders_created_date_idx ON orders ((DATE(created_at)));"
sudo mysql shop -E -e "EXPLAIN FORMAT=TRADITIONAL SELECT COUNT(*), SUM(total_cents) FROM orders WHERE DATE(created_at) = '2026-03-14'"The original query now uses orders_created_date_idx with type: ref. A functional index only matches the exact expression it was built on: DATE(created_at) is served, YEAR(created_at) is not.
If your users type text in mixed case or in several languages, the same rule applies to LOWER(email) or UPPER(name). With a utf8mb4 column on MySQL's default case-insensitive collation, email = 'X@Example.com' already ignores case, so the wrapper is often not needed at all.
Check it worked
The DATE(created_at) query moves from type: ALL to type: ref on orders_created_date_idx, and the rewritten range query uses orders_created_idx. Both return the same count when you run them without EXPLAIN.
Step 8 · Test a drop safely with an invisible index
You now have five indexes on orders, and orders_customer_idx looks redundant: orders_customer_created_idx starts with customer_id, so by the leftmost-prefix rule it can serve every lookup the single-column index can. Dropping an index on a large table is quick, but rebuilding it if you were wrong takes minutes to hours, and the slow queries arrive straight away.
An invisible index is still maintained on every write, but the optimiser ignores it. Hide the suspect and check the plan of a query that used to need it:
sudo mysql shop -e "ALTER TABLE orders ALTER INDEX orders_customer_idx INVISIBLE;"
sudo mysql shop -E -e "EXPLAIN FORMAT=TRADITIONAL SELECT * FROM orders WHERE customer_id = 1234"The plan shows type: ref with key: orders_customer_created_idx, so the composite index takes over. Hiding and showing an index is instant. On a live server you would leave it invisible for a few days, long enough to cover weekly jobs and month-end reports, while watching the slow query log from the next step. If anything gets slower, ALTER TABLE orders ALTER INDEX orders_customer_idx VISIBLE; puts it back at once.
A primary key cannot be made invisible, and a unique index still enforces uniqueness while invisible, so this test only tells you about read performance.
When you are confident, drop it:
sudo mysql shop -e "DROP INDEX orders_customer_idx ON orders;"
sudo mysql shop -e "SHOW INDEX FROM orders;"Check it worked
While the index was invisible, the plan used orders_customer_created_idx. After the drop, SHOW INDEX lists PRIMARY, orders_customer_created_idx (two rows, one per column), orders_created_idx and orders_created_date_idx, and no orders_customer_idx.
Step 9 · Find the next slow query with the slow query log
On your own server you rarely know which query to tune. The slow query log records every statement that takes longer than long_query_time seconds. SET PERSIST changes a setting now and saves it for restarts, so you do not have to edit a config file:
sudo mysql -e "SET PERSIST slow_query_log = ON; SET PERSIST long_query_time = 0.5;"
sudo mysql -e "SELECT @@slow_query_log, @@long_query_time, @@slow_query_log_file;"The output shows 1, 0.500000 and the path of the log file, by default the host name followed by -slow.log in the data directory. Half a second is a reasonable start for a web app; lower it as the worst offenders are fixed.
On a small dataset few queries cross that line, so also log the queries that use no index at all, whatever their speed. This is noisy, so turn it on only while you are investigating:
sudo mysql -e "SET GLOBAL log_queries_not_using_indexes = ON;"
sudo mysql shop -e "SELECT COUNT(*) FROM orders WHERE total_cents > 20000;"
sudo tail -n 8 "$(sudo mysql -N -s -e 'SELECT @@slow_query_log_file')"The entry at the end of the log shows Query_time, Rows_sent: 1 and Rows_examined: 500000, then the statement itself. A large gap between rows examined and rows sent is the same signal you read in EXPLAIN ANALYZE. Take the worst entry, run it under EXPLAIN ANALYZE and work through the steps above.
SET GLOBAL lasts until the next restart, so the noisy setting cannot outlive the investigation by accident. Turn it off when you are done:
sudo mysql -e "SET GLOBAL log_queries_not_using_indexes = OFF;"To confirm SET PERSIST saved the settings, restart the server and run SELECT @@slow_query_log, @@long_query_time; again:
sudo systemctl restart mysql
sudo mysql -e "SELECT @@slow_query_log, @@long_query_time;"The log grows without limit, so add it to log rotation, or truncate it after each review, on a long-lived server. If you are on a small VPS or prepaid bandwidth and pull logs to your laptop to read, copy only the tail rather than the whole file.
Check it worked
The tail output contains your SELECT COUNT(*) FROM orders WHERE total_cents > 20000 statement with Rows_examined: 500000. After a restart, SELECT @@slow_query_log, @@long_query_time; still shows 1 and 0.500000, because SET PERSIST saved them.
When you have finished practising, remove the database:
sudo mysql -e "DROP DATABASE shop;"Next steps
- Compare how PostgreSQL shows the same ideas, including index-only scans and statement statistics:
/tutorials/speed-up-slow-postgres-queries-with-explain. - Set up the server these steps assume, with a limited app user:
/tutorials/install-mysql-9-7-lts-on-ubuntu-26-04. - Protect the data before you change indexes on a live system:
/tutorials/back-up-and-restore-mysql-with-mysqldump-and-binary-logs.
Related tutorials
- How to Install MySQL 9.7 LTS on Ubuntu 26.04You will install MySQL 9.7 LTS from Oracle's official apt repository, close it to the network, create a database and a limited user for your app, and connect with a password.
- How to Find and Fix Slow PostgreSQL Queries with EXPLAIN ANALYZEYou will read a PostgreSQL 18 query plan, add an index that turns a 40 ms table scan into a 0.2 ms lookup, and use pg_stat_statements to find which queries deserve that effort.
- Back up and restore MySQL with mysqldump and binary logsYou will take consistent, compressed dumps of a MySQL 9.7 database with a private backup account, prove they restore, recover from an accidental DELETE by replaying the binary log up to the moment before it, and leave a nightly backup script running.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials