Most database outages in PHP, Node.js, and .NET applications are not caused by hardware limits—they happen when a single unindexed SELECT query scans millions of InnoDB or PostgreSQL pages on every HTTP request.
What Causes a Slow Query in MySQL InnoDB?
A query becomes slow when MySQL must examine far more rows than it returns (high rows_examined vs rows_sent), spill intermediate results to an on-disk temporary table (Using temporary), perform an unindexed sort (Using filesort), or wait on row/metadata locks.
Step-by-Step Workflow: Diagnose With EXPLAIN First
- Capture offending statements from
slow_query_log(setlong_query_time = 0.2andlog_queries_not_using_indexes = ONin staging). - Prefix the query with
EXPLAIN(orEXPLAIN ANALYZEon MySQL 8.0.18+) to inspect actual row counts and loop timings. - Check
type,key,rows, andExtrabefore creating or altering any index.
Example: Turning a Full Table Scan Into a Covering Composite Index
-- Slow query (scans 4.2M rows because YEAR() disables the created_at index):
SELECT id, customer_id, total_cents
FROM invoices
WHERE status = 'paid'
AND YEAR(created_at) = 2026
ORDER BY created_at DESC
LIMIT 50;
-- Step 1: Rewrite predicate to be SARGable (range on raw column):
SELECT id, customer_id, total_cents
FROM invoices
WHERE status = 'paid'
AND created_at >= '2026-01-01 00:00:00'
AND created_at < '2027-01-01 00:00:00'
ORDER BY created_at DESC
LIMIT 50;
-- Step 2: Equality column FIRST, range/sort column SECOND, selected columns INCLUDED:
CREATE INDEX idx_invoices_status_created_cover
ON invoices (status, created_at DESC, customer_id, total_cents);
Before creating large composite indexes on production tables, model the RAM and disk impact with our SQL Index Size Calculator and compare scan vs seek I/O with the SQL Cost Calculator.
Reading MySQL EXPLAIN Access Types (Fastest to Slowest)
EXPLAIN type |
Meaning | Production Action |
|---|---|---|
const / eq_ref |
At most 1 row matched via primary or unique key | Optimal — no change needed |
ref |
Indexed equality lookup matching multiple rows | Healthy if selectivity is tight |
range |
B-Tree range scan (BETWEEN, >=, IN) |
Verify Extra avoids filesort |
index |
Full scan of an entire index tree | Reorder composite index columns |
ALL |
Full clustered table scan across all data pages | Critical on large tables — add SARGable index |
Fixing Deep OFFSET Pagination on Million-Row Tables
LIMIT 50 OFFSET 100000 forces MySQL to fetch and discard 100,050 rows. Replace deep offsets with keyset cursor pagination:
SELECT id, customer_id, total_cents, created_at
FROM invoices
WHERE status = 'paid'
AND (created_at, id) < ('2026-11-15 14:22:10', 984120)
ORDER BY created_at DESC, id DESC
LIMIT 50;
Common Mistakes & InnoDB Tuning Checklist
- Putting range columns before equality columns: In
INDEX (created_at, status), a range condition oncreated_atprevents MySQL from usingstatusfor B-Tree narrowing. Always put equality (=) columns leftmost. - Undersized
innodb_buffer_pool_size: On dedicated database servers (or when sizing managed RDS / Cloud SQL instances), allocate 65–75% of RAM to the InnoDB buffer pool so hot index pages stay in memory. - Duplicate left-prefix indexes: If you already have
INDEX (user_id, created_at), a separateINDEX (user_id)is usually redundant write overhead.
Frequently Asked Questions
Why did MySQL choose a full table scan even though an index exists?
When a predicate matches roughly 15–25% or more of table rows, random bookmark lookups from a secondary index back to the clustered primary key cost more I/O than reading clustered data pages sequentially. A covering index (Using index) eliminates those bookmark lookups.
Diagnosing `Using temporary` and `Using filesort` in GROUP BY Queries
Even when your `WHERE` clause uses an index, MySQL falls back to creating an internal temporary table and sorting rows when `GROUP BY` and `ORDER BY` reference columns in a different order—or reference columns across two joined tables! Align your composite index columns so MySQL satisfies filtering, grouping, and sorting in a **single ordered index scan**:
-- Slow: Filters by tenant_id, groups by category_id, sorts by SUM() -> triggers temporary + filesort
SELECT category_id, COUNT(*) AS items_count, SUM(price_cents) AS revenue_cents
FROM order_items
WHERE tenant_id = 42
AND created_at >= '2026-01-01'
GROUP BY category_id;
-- Optimal Loose/Ordered Index Scan when grouping by equality-filtered prefix:
CREATE INDEX idx_order_items_tenant_cat_created
ON order_items (tenant_id, category_id, created_at, price_cents);
Monitoring Index Bloat, Unused Indexes & Lock Waits With `sys` Schema
Every extra secondary index slows down `INSERT`, `UPDATE`, and `DELETE` operations and consumes precious `innodb_buffer_pool_size` RAM. On MySQL 8.0/8.4, query the built-in `sys` schema to spot unused and redundant indexes safely after your server has been running production traffic for at least 14 days:
-- 1. Find secondary indexes with ZERO read operations since server startup:
SELECT object_schema, object_name, index_name
FROM sys.schema_unused_indexes
WHERE object_schema NOT IN ('mysql', 'sys', 'performance_schema');
-- 2. Find redundant left-prefix duplicate indexes (including exact DROP DDL!):
SELECT table_schema, table_name, redundant_index_name, dominant_index_name, sql_drop_index
FROM sys.schema_redundant_indexes;
In MySQL 8.0+, never drop a suspect index blindly—make it **invisible** first (`ALTER TABLE orders ALTER INDEX idx_legacy INVISIBLE;`)! The optimizer immediately stops using an invisible index while InnoDB continues maintaining it on disk. If slow-query metrics remain healthy for 48 hours, drop it permanently; if a monthly cron report suddenly slows down, restore it in 5 milliseconds with `ALTER INDEX idx_legacy VISIBLE` instead of waiting 40 minutes to rebuild a 50 GB B-Tree!
Connection Pooling & Transaction Lifetime Rules
- Never make external HTTP, Stripe, or OpenAI API calls inside `START TRANSACTION ... COMMIT`: Holding row locks across a 1.5-second external network call causes cascading `Lock wait timeout exceeded; try restarting transaction (Error 1205)` failures under concurrent traffic. Compute external API results *before* opening the database transaction, or persist an outbox job row and process external calls asynchronously.
- Inspect query anti-patterns automatically: Paste any slow query from your application logs into our SQL Query Analyzer before running `EXPLAIN ANALYZE`.