MySQL performance tuning queries are most useful when they reduce guesswork. A slow application does not automatically mean that MySQL needs more memory, a new index, or a larger server. The delay may come from one expensive statement, many individually small statements, lock contention, connection pressure, storage latency, or work performed outside the database.
The safest tuning process is evidence first: capture the workload, rank the cost, inspect the execution plan, make one controlled change, and compare the result. The queries below are designed for diagnosis and trend review. Test them with an account that has only the required monitoring privileges, and validate any change in a representative environment before applying it to production.
Start with a repeatable tuning workflow
A useful investigation separates symptoms from causes. Record the time window, affected endpoint or job, expected latency, observed latency, deployment history, traffic level, and whether the problem is continuous or intermittent. Then collect database evidence for the same window.
- Confirm the symptom: measure application latency and error rate rather than relying on a general report that “the database is slow.”
- Rank statement cost: find statements consuming the most total time, not only the single slowest execution.
- Check concurrency: inspect active sessions, lock waits, connection use, and transaction age.
- Inspect access paths: use
EXPLAINand, when safe,EXPLAIN ANALYZE. - Change one variable: rewrite SQL, add or adjust an index, reduce returned data, or alter application behavior.
- Verify: compare latency, rows examined, executions, locks, CPU, and I/O over an equivalent workload window.
Keep a before-and-after record. A query that becomes faster but increases write cost, storage, lock duration, or memory consumption may not be a net improvement.
Confirm the MySQL version and observation features
Version and configuration determine which diagnostic tables and fields are available. Begin with a small environment snapshot:
SELECT VERSION() AS mysql_version;
SHOW VARIABLES WHERE Variable_name IN (
'performance_schema',
'slow_query_log',
'long_query_time',
'log_queries_not_using_indexes',
'max_connections'
);
SHOW GLOBAL STATUS WHERE Variable_name IN (
'Uptime',
'Threads_connected',
'Threads_running',
'Connections',
'Aborted_connects',
'Slow_queries'
);
Do not enable every consumer or instrument blindly on a busy server. Performance Schema is designed for production observability, but the enabled detail should match the question you are investigating. The slow query log also needs careful retention and access controls because SQL can contain sensitive values.
Find statements consuming the most total time
Performance Schema statement digests group similar SQL while replacing literal values. This makes the summary useful for identifying workload patterns. The following query ranks normalized statements by total execution time:
SELECT
SCHEMA_NAME,
DIGEST_TEXT,
COUNT_STAR AS executions,
ROUND(SUM_TIMER_WAIT / 1000000000000, 2) AS total_seconds,
ROUND(AVG_TIMER_WAIT / 1000000000, 2) AS avg_ms,
SUM_ROWS_EXAMINED AS rows_examined,
SUM_ROWS_SENT AS rows_sent,
SUM_CREATED_TMP_DISK_TABLES AS disk_tmp_tables,
SUM_SORT_MERGE_PASSES AS sort_merge_passes
FROM performance_schema.events_statements_summary_by_digest
WHERE SCHEMA_NAME IS NOT NULL
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 20;
Total time answers “where does the database spend its time?” Average latency answers a different question. A statement averaging 20 milliseconds but executing a million times can consume more capacity than a five-second report that runs once. Review executions, total time, average time, rows examined, and rows returned together.
Detect scan-heavy and inefficient query patterns
A high ratio of rows examined to rows sent often indicates avoidable work, although analytical and batch queries can legitimately scan many rows. This query highlights frequently executed digests that inspect much more data than they return:
SELECT
SCHEMA_NAME,
DIGEST_TEXT,
COUNT_STAR AS executions,
SUM_ROWS_EXAMINED AS rows_examined,
SUM_ROWS_SENT AS rows_sent,
ROUND(SUM_ROWS_EXAMINED / NULLIF(SUM_ROWS_SENT, 0), 1)
AS examined_per_row_sent,
ROUND(AVG_TIMER_WAIT / 1000000000, 2) AS avg_ms
FROM performance_schema.events_statements_summary_by_digest
WHERE SCHEMA_NAME IS NOT NULL
AND COUNT_STAR >= 10
AND SUM_ROWS_EXAMINED > 0
ORDER BY examined_per_row_sent DESC, SUM_TIMER_WAIT DESC
LIMIT 20;
Investigate the leading candidates with their schema, data distribution, predicates, joins, ordering, and selected columns in mind. Common causes include missing composite indexes, an index whose leading columns do not match the filter, functions applied to indexed columns, implicit type conversions, wildcard prefixes, and returning far more rows than the caller needs.
Use the slow query log for event-level evidence
MySQL slow query monitoring complements digest summaries by preserving individual events. Configure thresholds deliberately: a threshold that is too high misses cumulative pain, while a very low threshold can create excessive log volume. During a bounded investigation, review the current settings and adjust only through an approved change process.
SHOW VARIABLES LIKE 'slow_query_log%';
SHOW VARIABLES LIKE 'long_query_time';
SHOW VARIABLES LIKE 'min_examined_row_limit';
SHOW GLOBAL STATUS LIKE 'Slow_queries';
Tools such as mysqldumpslow or pt-query-digest can aggregate a protected copy of the log. Compare counts, total response time, percentiles, lock time, and rows examined. Redact or restrict sensitive SQL before sharing reports.
Inspect current sessions without confusing idle with busy
Connection count alone does not prove pressure. Distinguish sleeping sessions from running work and identify sessions that remain active unusually long:
SELECT
PROCESSLIST_ID AS connection_id,
PROCESSLIST_USER AS user_name,
PROCESSLIST_HOST AS client_host,
PROCESSLIST_DB AS database_name,
PROCESSLIST_COMMAND AS command_name,
PROCESSLIST_TIME AS seconds_in_state,
PROCESSLIST_STATE AS state_name,
LEFT(PROCESSLIST_INFO, 300) AS statement_text
FROM performance_schema.threads
WHERE TYPE = 'FOREGROUND'
AND PROCESSLIST_ID IS NOT NULL
ORDER BY PROCESSLIST_TIME DESC;
Long-lived sleeping connections may be normal for a pool. Long-running active statements, rapid connection churn, growing Threads_running, or repeated aborted connections deserve investigation. Compare these values against the application pool configuration and the server's max_connections; simply increasing the limit can amplify contention or memory pressure.
Find InnoDB lock waits and blocking transactions
Lock contention can make otherwise efficient SQL appear slow. On supported MySQL 8 installations, the sys.innodb_lock_waits view provides a readable starting point:
SELECT
wait_age,
locked_table,
locked_index,
waiting_pid,
blocking_pid,
LEFT(waiting_query, 300) AS waiting_query,
LEFT(blocking_query, 300) AS blocking_query
FROM sys.innodb_lock_waits
ORDER BY wait_age_secs DESC;
Also inspect transactions that have remained open. A transaction can hold locks even when its connection is not currently running a statement:
SELECT
trx_id,
trx_state,
trx_started,
trx_wait_started,
trx_mysql_thread_id,
trx_rows_locked,
trx_rows_modified,
LEFT(trx_query, 300) AS trx_query
FROM information_schema.innodb_trx
ORDER BY trx_started;
Do not terminate a blocker automatically from a monitoring script. First identify the application owner, transaction purpose, rollback cost, and business impact. The durable fix is often shorter transaction scope, consistent row-access order, smaller batches, or corrected error handling.
Read execution plans carefully
After ranking a candidate, run EXPLAIN with representative parameter values. Check join order, access type, chosen key, estimated rows, filtering, temporary tables, and filesorts.
EXPLAIN FORMAT=TREE
SELECT o.id, o.created_at, c.name
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE o.status = 'pending'
AND o.created_at >= CURRENT_DATE - INTERVAL 7 DAY
ORDER BY o.created_at DESC
LIMIT 100;
EXPLAIN ANALYZE executes the statement and reports actual timing and row counts. It can be valuable for read-only queries in a safe environment, but do not apply it casually to expensive or data-changing SQL in production. For sensitive workloads, reproduce the plan against a representative staging dataset or use plain EXPLAIN first.
Large differences between estimated and actual rows can point to skewed data, stale statistics, correlated predicates, or a plan that needs a different index. Avoid adding every apparently useful index: each index consumes storage and adds work to inserts, updates, deletes, backups, and maintenance.
Check temporary-table and sort pressure
Disk-based temporary tables and merge passes can expose query shapes that spill beyond available memory or cannot use an appropriate access path:
SHOW GLOBAL STATUS WHERE Variable_name IN (
'Created_tmp_tables',
'Created_tmp_disk_tables',
'Sort_merge_passes',
'Sort_rows',
'Sort_scan'
);
Use rates over time rather than raw counters because global status values accumulate since startup. A growing count can reflect increased traffic rather than worsening efficiency. Correlate the rate with statement digests, response time, memory use, and storage latency before changing buffer limits.
Measure trends instead of relying on one snapshot
MySQL slow query trends are more actionable than an isolated top-ten list. Capture a consistent set of indicators at regular intervals:
- statement executions, total time, average time, rows examined, and rows sent;
- running and connected threads, connection errors, and aborted connections;
- lock waits, deadlocks, long transactions, and rollback events;
- temporary tables, sort activity, buffer-pool behavior, and redo pressure;
- database size and growth, filesystem capacity, I/O latency, and backup status; and
- application latency, traffic, deployments, and scheduled batch work.
Counter deltas should be normalized by time or workload. Keep server restart times with the samples so a counter reset is not mistaken for improvement. Weekly review is often enough for gradual capacity and query-pattern changes, while incident diagnostics may need minute-level evidence for a bounded period.
Verify each tuning change
Define success before making a change. For a query rewrite or index, that might mean lower p95 latency, fewer rows examined, reduced total statement time, and no unacceptable increase in write latency or storage. Compare equivalent traffic windows and watch long enough to include background jobs and peak behavior.
If the change does not meet the target, revert it or continue the investigation rather than stacking unrelated adjustments. Document the original plan, changed plan, schema change, measured result, and rollback path. This discipline makes later incidents faster because the team can see what was tried and why.
A practical MySQL query tuning checklist
- Confirm the user-visible symptom and exact time window.
- Rank digests by total cost, average latency, executions, and rows examined.
- Review slow-log events for parameter-specific behavior and outliers.
- Check active work, connection pressure, lock waits, and transaction age.
- Inspect execution plans with representative values.
- Consider query shape and data access before changing global settings.
- Make one reversible change and measure an equivalent workload.
- Track the result alongside host, storage, and application signals.
Good MySQL slow query analysis turns a vague performance complaint into a ranked, testable problem. The key is not collecting every metric; it is preserving enough consistent evidence to connect a costly statement or contention event to its application impact.
Want MySQL trends without another dashboard to watch?
DMCloud Architect turns Linux and MySQL health signals into a practical weekly report, helping developers and small businesses spot query, capacity, and infrastructure risks early.