Back to Blog
MySQL Performance Tuning Queries: A Practical Diagnostic Playbook

MySQL Performance Tuning Queries: A Practical Diagnostic Playbook

   Mariusz Antonik    Database    9 min read    34 views

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.

  1. Confirm the symptom: measure application latency and error rate rather than relying on a general report that “the database is slow.”
  2. Rank statement cost: find statements consuming the most total time, not only the single slowest execution.
  3. Check concurrency: inspect active sessions, lock waits, connection use, and transaction age.
  4. Inspect access paths: use EXPLAIN and, when safe, EXPLAIN ANALYZE.
  5. Change one variable: rewrite SQL, add or adjust an index, reduce returned data, or alter application behavior.
  6. 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.

Explore Infrastructure Health Reporting.

About the Author
Mariusz Antonik

Oracle Cloud Infrastructure expert and consultant specializing in database management and automation.

All Tags
#active-directory #adcli #Advanced #agent-visibility #agentless-monitoring #alerts #amazon-linux-2023 #argo-cd #asset-inventory #atop #auditd #automation #backend-infrastructure #backup-monitoring #backup-setup #backup-verification #backups #bandwidth-monitoring #bare-metal-server #baseline-delta-monitoring #Bash #bash cpu monitoring script #bash monitoring #bash scripting #bash-automation #bash-script #bash-scripts #Beginner #Best Practices #bind-dns #block volume backup #brute-force-protection #canary-deployment #Capacity Planning #career-development #centos-7 #centos-ftp-migration #centralized-logging #change-management #chromebook-linux #ci-cd #cifs-mounts #clonezilla #cloud backup strategy #cloud-administration #cloud-costs #cloud-database-setup #cloud-networking #cloudflare-workers #cluster-administration #compute #configuration-management #container-monitoring #control-panel-security #cpu bottleneck #CPU Monitoring #cpu monitoring linux #cpu monitoring script linux #cpu trends #cpu usage trends #cpu usage trends linux #cpu-monitoring-script #cpu-monitoring-without-tools #cpu-performance-decline-server #cpu-performance-degradation-linux #cpu-performance-trends-linux #cpu-pressure #cpu-pressure-linux #cpu-reporting-linux-server #cpu-saturation #cpu-usage-history-linux #create oracle db system in oci #cron #cron cpu monitoring #cron cpu monitoring linux #cron jobs #cron-automation #cron-monitoring #custom-linux-distribution #cve-2026-98432 #cve-advisory #data-sanitization #database #database monitoring #database performance #database-health #database-migration #database-setup #debian #deployment-checklist #detect slow queries mysql #devops #devops-career #devops-checklist #devops-help #devops-interview #devops-learning #disaster-recovery #disk capacity planning server #disk forecasting linux #disk growth trend linux #Disk Monitoring #disk usage #disk usage script linux #disk usage trends #disk-capacity #disk-growth #disk-io #disk-saturation-detection-linux #disk-scaling-planning-linux #disk-space-monitoring #disk-usage-history-linux #dns-migration #dnssec #Early Detection #easy infrastructure monitoring #ebpf #egress-monitoring #elasticsearch #exposed-port-monitoring #fail2ban #field-server-checklist #firewall-rules #fleet-ops #free-tier #freelance-sysadmin #gitlab-ci #gitops-security #growth-trends #Guide #health dashboards #Health Reporting #historical server monitoring #historical-monitoring #home-lab #how to monitor cpu usage linux #hpc #http-boot #https-certificates #incident-response #infiniband #infrastructure #infrastructure health #infrastructure health dashboard #infrastructure health reporting #infrastructure monitoring #infrastructure monitoring report #infrastructure trends #infrastructure trends monitoring #Infrastructure Visibility #infrastructure-as-code #infrastructure-automation #infrastructure-checklist #infrastructure-operations #infrastructure-reporting #inode-monitoring #interview-prep #ip-allowlist #iproute2 #it-asset-disposal #journald #kernel-patching #kubernetes-security #kvm #latency-checks #lightweight linux monitoring #lightweight monitoring #lightweight-monitoring-solution #linux #linux administration #linux cpu monitoring #linux cpu usage #linux disk capacity planning #linux disk usage #Linux monitoring #linux monitoring setup #linux monitoring tools #linux performance #linux performance monitoring #linux server #linux server monitoring #linux servers #linux storage #linux tools #linux-admin #linux-automation #linux-commands #linux-disk-monitoring #linux-file-sharing #linux-hardening #linux-health #linux-home-lab #linux-hotspot #linux-maintenance #linux-migration #linux-monitoring-for-small-business #linux-monitoring-script #linux-monitoring-small-business #linux-multi-seat #linux-networking #linux-patch-management #linux-performance-tuning #linux-plus #linux-remote-desktop #linux-security #linux-server-hardening #linux-server-health #linux-server-health-checks #linux-troubleshooting #lmod #local-dns #local-network #log-management #log-retention #logrotate #loki #low maintenance monitoring #lpic-1 #luks2 #machine-password-rotation #mkcert #monitor cpu usage over time linux #monitor linux server health #monitor server trends #monitor small production server #monitor-server-trends-over-time #monitoring #monitoring without complexity #monitoring-agent #monitoring-for-lean-teams #monitoring-without-devops-team #mptcp #MySQL #mysql health reporting #MySQL monitoring #mysql optimization #MySQL Performance #mysql performance degradation #mysql performance monitoring #mysql performance trends #mysql query performance issues #mysql server monitoring #mysql slow queries #mysql slow query analysis #mysql slow query monitoring #mysql trends #mysql-health #mysql-health-check #mysql-heatwave #mysql-indexing #mysql-monitoring-lightweight #mysql-monitoring-production #mysql-performance-visibility #mysql-query-degradation #mysql-query-latency #mysql-slow-query #mysql-workload-trends #network-automation #network-exposure #network-monitoring #network-traffic #networking #networkpolicy #nftables #node-express #nsg #observability #OCI #oci backup #oci bastion tutorial #oci block volume #oci infrastructure as code #OCI monitoring #oci networking #oci oracle database private subnet setup #oci oracle database tutorial #oci security #oci setup guide #oci terraform tutorial #oci tutorial for beginners #oci vcn terraform #oci virtual machine db system guide #oci-database #oci-mysql-heatwave #oci-mysql-heatwave-tutorial #oci-subnets #offline-pwa #open-port-monitoring #open-source-monitoring #openhpc #operations-checklist #oracle base database service tutorial #oracle cloud bastion #oracle cloud free tier tutorial #oracle cloud infrastructure step by step #oracle cloud infrastructure tutorial #oracle cloud storage #oracle database on oci setup #oracle-cloud #oracle-cloud-mysql-database-service #oracle-cloud-mysql-setup #oracle-cloud-vcn-setup #oracle-linux #oracle-linux-9 #outbound-connections #patch-compliance #patch-management #path-mtu-discovery #Performance #Performance Degradation #performance monitoring #performance trend monitoring #performance trends #performance-analysis #performance-schema #performance-troubleshooting #ping-monitoring #plan disk growth server #plesk #practical server monitoring #practical-linux-monitoring #predict disk usage growth #private instance access #process-monitoring #production-database #production-troubleshooting #prometheus #proxmox #Python #query optimization #query-trends #query-tuning #remote-workstation-security #rhel-tuned #rollback #route-tables #rsyslog #rtnetlink #samba-server #Security #security lists #security-audit #security-baseline #security-compliance #security-hardening #security-monitoring #selinux #server #server health #server health reporting #server health weekly report #server monitoring #Server Performance #server trend analysis #server-administration #server-audit #server-checklist #server-decommissioning #server-diagnostics #server-hardening #server-health-check #server-health-checklist #server-health-insights #server-health-summary #server-management #server-metrics #server-operations #server-reporting #server-security #server-security-audit #server-security-checklist #server-throughput #server-trends #server-troubleshooting #server-uptime #servers #service-worker #shutdown-protection #siem #simple cpu monitoring linux #simple linux monitoring #simple monitoring small business #simple monitoring system #simple ops monitoring #slow queries #slow query reporting mysql #slow-query-log #slurm #small business infrastructure #small business IT #small business servers #small infrastructure monitoring #small server monitoring #small-business-monitoring #small-business-security #small-business-server-monitoring #small-business-tech #software-support-engineer #sosreport #source-built-linux #ssh #ssh bastion #ssh-monitoring #ssh-security #sssd #storage capacity planning linux #storage monitoring #storage-capacity #storage-forecasting #subnets #sudo-security #support-engineer-interview #sysadmin-checklist #sysadmin-lab #syscall-monitoring #sysstat #System Health #system health reporting #system-administration #system-monitoring #systemd #tcp-mtu-probing #tcp-tuning #technical-documentation #technical-support #terraform oci compute #terraform oracle cloud infrastructure #track-disk-growth-linux #training-lab #Trend Monitoring #trend-analysis #trends #Troubleshooting #tuned-adm #Tutorial #ubuntu #ufw #uptime-checks #uptime-monitoring #used-server-hardware #vcn #vcn-design #vector #vps-management #vps-monitoring #vps-setup #vsftpd #vulnerability-management #vulnerability-response #wazuh #weekly-checklist #weekly-health-report #weekly-health-reporting #weekly-health-reports #weekly-reports #weekly-server-report #windows-admin #windows-agent #windows-linux #xrdp