The symptom
MySQL is slow: a query takes seconds, the server runs hot, or the app times out at peak hours. On MySQL 8.0 and later, performance_schema is on by default and the sys schema is installed, so everything below works on a stock server. Changing global variables needs SYSTEM_VARIABLES_ADMIN (or the older SUPER); reading performance_schema needs SELECT on it.
Diagnose it
Capture the offenders with the slow query log
The log records each slow statement with its real time, rows examined and rows sent:
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 0.5;
SET GLOBAL log_queries_not_using_indexes = 'ON';
SHOW VARIABLES LIKE 'slow_query_log_file';
Two catches: a new long_query_time only applies to connections opened after the change, and SET GLOBAL is lost on restart (use SET PERSIST to keep it). log_queries_not_using_indexes logs every unindexed statement however fast it was, so watch the file's growth on a busy server. Aggregate the file with mysqldumpslow, which ships with MySQL, or Percona's pt-query-digest. For a live ranking without the log, use the digest table:
SELECT DIGEST_TEXT, COUNT_STAR,
round(AVG_TIMER_WAIT / 1e12, 3) AS avg_seconds,
round(SUM_TIMER_WAIT / 1e12, 1) AS total_seconds
FROM performance_schema.events_statements_summary_by_digest
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 10;
Timer columns in performance_schema are in picoseconds, hence the 1e12. Digests replace literals with ?, so one row covers every run of the same statement shape; the counters run from server start or the last TRUNCATE TABLE on the table. The sys schema wraps the same data with friendlier names: sys.statements_with_full_table_scans y sys.statements_with_temp_tables list the usual suspects directly.
Read the plan with real timings
MySQL 8.0.18 and newer can run the statement for real:
EXPLAIN ANALYZE
SELECT o.id, o.total, c.email
FROM orders AS o JOIN customers AS c ON c.id = o.customer_id
WHERE o.status = 'pending'
AND o.created_at >= NOW() - INTERVAL 7 DAY;
The tree shows, per iterator, the estimated cost and rows next to the actual time (first row..all rows, in milliseconds), rows and loops. Look for Table scan on o under a Filter whose actual rows are a small fraction of the scan's: that is MySQL reading the whole table to keep a handful of rows. Multiply time and rows by loops for anything inside a nested loop. On servers older than 8.0.18, plain EXPLAIN más SHOW WARNINGS still shows the chosen keys, the rows estimate and the rewritten query. MariaDB has no EXPLAIN ANALYZE; its equivalent is ANALYZE FORMAT=JSON SELECT .... Format both the query and the plan output with the Formateador SQL when they arrive as one long line from the log.
Check the buffer pool hit rate
SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%';
Divide Innodb_buffer_pool_reads (reads InnoDB had to take from disk) by Innodb_buffer_pool_read_requests (logical reads). Both count from server start, so take two readings a few minutes apart and divide the differences. If disk reads stay above a fraction of a percent of requests on a busy server, the working set does not fit in the pool - the memory pressure guide covers the sizing. If a query blocks or deadlocks rather than runs slow, the blocking and deadlocks guide takes over from here.
Fix it
Index the columns the scan touches. InnoDB uses the leftmost prefix of an index, so put the equality column first and the range column last, and append the selected columns to skip the table lookups:
ALTER TABLE orders
ADD INDEX idx_orders_status_created (status, created_at, customer_id, total);
Refresh the optimizer's statistics if the plan changed for no reason, and re-run EXPLAIN ANALYZE afterwards:
ANALYZE TABLE orders;
Keep the working set in memory. If the hit rate is poor, raise innodb_buffer_pool_size (on a dedicated server, commonly 60-75% of RAM). It has been resizable online with SET GLOBAL since MySQL 5.7.5; the resize runs in the background in chunks of innodb_buffer_pool_chunk_size, and you still need SET PERSIST or the config file to keep it after a restart.
Let unused indexes go. Every index costs something on every write; sys.schema_unused_indexes lists indexes with no recorded use since the server started. A server restarted last week has not seen your month-end jobs yet, so check uptime before dropping anything. MySQL 8.0 can make an index invisible (ALTER TABLE orders ALTER INDEX idx_name INVISIBLE;) to test the drop without losing the index.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Turn on the slow query log with long_query_time = 0.5 and reconnect so the new threshold applies.
- Aggregate the log (mysqldumpslow or pt-query-digest) or read the top digests from performance_schema.
- EXPLAIN ANALYZE the worst query; note every full table scan and the rows it processes.
- Check the index exists and its leftmost prefix matches the WHERE clause order.
- ANALYZE TABLE the hot tables if the plan looks wrong for the data you know.
- Add one covering index with equality columns first and range columns last.
- Compute the buffer pool hit rate; if disk reads dominate, size the pool to the working set.
- Review sys.schema_unused_indexes after a full business cycle of uptime; make a candidate INVISIBLE before dropping it.
Questions that come up
The query is fast in my test client and slow in production. Why?
Plans depend on data volume and buffer pool warmth, not just on the SQL. In production the table may be a hundred times larger, the working set may not fit in memory, or the cached plan was built for different statistics. EXPLAIN ANALYZE on the production server is the only measurement that counts.
Does log_queries_not_using_indexes slow the server down?
The logging itself is cheap, but on a server with many unindexed statements the log file can grow to gigabytes an hour, and that I/O is not free. Turn it on to hunt for a day, aggregate, then turn it off until the next hunt.
Why doesn't MySQL use my index on created_at?
The most common reasons: the predicate wraps the column in a function (DATE(created_at) = ...), the index's leftmost column is not in the predicate, or the optimizer estimates the range covers too much of the table and a scan is cheaper. Compare the estimate in EXPLAIN's rows column with the table's actual row count before blaming the optimizer.
How big should innodb_buffer_pool_size be?
Big enough to hold the hot working set - the pages actually read repeatedly - which is usually far smaller than the whole database. Watch the hit rate from Innodb_buffer_pool_read%: if reads from disk are rare in steady state, the pool is big enough; raising it further only helps writes and scans marginally.
What is the fastest way to find queries burning CPU?
Order performance_schema.events_statements_summary_by_digest by SUM_TIMER_WAIT and look at SUM_ROWS_EXAMINED next to SUM_ROWS_SENT. Most MySQL CPU goes into reading and filtering rows, so a digest that examines millions of rows to send a handful is the usual culprit. sys.statements_with_full_table_scans lists the same offenders - see the high CPU guide for the full method.