Software Engineering
MySQL Indexing and Query Performance: The Practical Guide Every Backend Dev Needs
Most “slow database” problems are missing or misused indexes. Learn how indexes work, how to read EXPLAIN, and the habits that keep queries fast as data grows.
By Philip Mutuku · Published · Updated · 5 min read
Your app feels instant with 500 rows. At 5 million, one page takes eight seconds, and the server CPU is pinned. Nothing in the code changed. What changed is that the database now has to read millions of rows to find the dozen you asked for. Indexes are how you stop that.
How an index works
Without an index, MySQL answers a query by scanning every row in the table (a full table scan). An index is a separate, sorted structure, a B-tree in InnoDB, that lets the database jump straight to matching rows, much like the index at the back of a book.[1]
The trade-off: indexes speed up reads but slow down writes (every insert and update must maintain them) and use disk space. So the aim is not “index everything” but “index what you query”.
Always start with EXPLAIN
Never guess. Put EXPLAIN in front of a query and MySQL shows how it plans to run it.[3] The columns that matter most:
| Column | What to look for |
|---|---|
| type | ALL means a full table scan (bad on big tables). ref, range, eq_ref and const are index lookups (good). |
| key | The index actually chosen. NULL means none was used. |
| rows | Estimated rows examined. Compare it with the rows you actually return. |
| Extra | Using filesort or Using temporary often signals a costly sort or temp table. |
-- A common slow query on a growing orders table
EXPLAIN
SELECT id, total, created_at
FROM orders
WHERE customer_id = 8841
AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;
-- If "type" is ALL and "rows" is in the millions, add a composite index:
CREATE INDEX idx_orders_customer_status_created
ON orders (customer_id, status, created_at);
Composite indexes and column order
A multi-column index is only fully useful from its leftmost columns: an index on (customer_id, status, created_at) can serve queries filtering on customer_id, or customer_id and status, but not on status alone.[2] A good rule for ordering: put columns tested with equality first, then the column used for range or sorting last. The index above lets MySQL find a customer’s paid orders already sorted by date, with no extra sort step.
Common ways to accidentally defeat an index
- Functions on the column. WHERE YEAR(created_at) = 2026 cannot use an index on created_at. Rewrite as a range: created_at >= '2026-01-01' AND created_at < '2027-01-01'.
- Leading wildcards. LIKE '%mwangi' forces a scan; LIKE 'mwangi%' can use an index. For real text search use a full-text index or a search engine.
- Type mismatches. Comparing a string column with a number makes MySQL convert every row.
- **SELECT * everywhere.** It pulls unneeded columns and prevents covering-index optimisations.
- OFFSET paging deep into results. OFFSET 500000 still reads and discards 500,000 rows. Use keyset (cursor) pagination.
-- Slow on deep pages: reads and throws away 500,000 rows
SELECT id, title FROM articles ORDER BY id DESC LIMIT 20 OFFSET 500000;
-- Fast at any depth: continue from the last id the client saw
SELECT id, title FROM articles WHERE id < 412345 ORDER BY id DESC LIMIT 20;
The N+1 problem
Perhaps the most common application-level performance bug: loading 50 orders, then running a separate query for each order’s customer, 51 queries where 1 or 2 would do. Use a JOIN, or fetch related rows in one batched IN (…) query. Many ORMs hide this, so turn on query logging in development and watch for repeated near-identical statements.
Finding the queries that actually hurt
Guessing which query is slow wastes time. Enable the slow query log with a modest threshold, such as one second, and review it regularly. Group similar queries and rank them by total time rather than by the single slowest run, because a moderately slow query that runs thousands of times a minute can hurt more than a rare slow report.
-- Enable the slow query log (adjust for your environment)
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
-- Then inspect a suspect query
EXPLAIN SELECT o.id, o.total
FROM orders o
WHERE o.customer_id = 42
AND o.status = 'paid'
ORDER BY o.created_at DESC
LIMIT 20;
In the EXPLAIN output, look at type (aim to avoid ALL, a full table scan), key (which index was chosen), rows (how many rows MySQL expects to examine) and Extra (warnings such as Using filesort or Using temporary). A composite index on (customer_id, status, created_at) would serve the query above well.
Indexes are not free
Every index speeds up some reads but slows down inserts, updates and deletes, and uses disk and memory. Adding an index for every column is a common mistake. Create indexes for real query patterns, remove duplicates and unused ones, and check how often an index is used before deciding to keep it.
- Avoid indexing columns with very few distinct values on their own, such as a yes/no flag.
- Keep indexed columns short; long text columns make large, slow indexes.
- Watch for redundant indexes: an index on
(a, b)already covers queries onaalone. - Re-run
EXPLAINafter changes to confirm the optimiser uses the new index.
Operational habits that prevent surprises
- Test with production-sized data. A query that is fast on a hundred rows can crawl on ten million.
- Run schema changes carefully. Adding an index on a large table can lock or slow writes; use online schema change tools or schedule quiet periods.
- Use connection pooling and set sensible limits so a spike does not exhaust the server.
- Keep backups and test restores, including point-in-time recovery for important data.
- Monitor query throughput, replication lag, disk space and buffer pool efficiency.
Frequently asked questions
Does MySQL still need indexes if we cache with Redis?
Yes. Caching reduces repeated reads, but cache misses, writes and background jobs still hit the database. Indexes keep those paths fast and protect you when the cache is cold or fails.
When should we move to a read replica or sharding?
Only after you have fixed queries and indexes and still have load problems. Replicas help with read-heavy workloads; sharding adds major complexity and should be a last resort.
Habits that keep it fast
- Enable the slow query log and review the worst offenders weekly.
- Test with realistic data volumes. A query that is fine on 1,000 rows tells you nothing about 10 million.
- Index foreign keys and columns used in frequent WHERE, JOIN and ORDER BY clauses.
- Drop unused indexes. They cost every write and give nothing back.
- Cache expensive, rarely changing results instead of recomputing them on every request.
Learn to read EXPLAIN and a handful of indexing rules, and you will fix most performance problems before they become incidents.
References & further reading
- MySQL 8.0 Reference Manual, “How MySQL Uses Indexes”. https://dev.mysql.com/doc/refman/8.0/en/mysql-indexes.html
- MySQL 8.0 Reference Manual, “Multiple-Column Indexes”. https://dev.mysql.com/doc/refman/8.0/en/multiple-column-indexes.html
- MySQL 8.0 Reference Manual, “EXPLAIN Statement” and “EXPLAIN Output Format”. https://dev.mysql.com/doc/refman/8.0/en/explain.html