To fix slow MySQL queries, identify the statements consuming database time, inspect their execution plans, and address the underlying cause. This MySQL 8.0/8.4 workflow covers five common problems: inefficient indexes, N+1 queries, connection pressure, repeated reads, and lock contention. Start with evidence before changing configuration.
Key takeaways
- Rank cumulative database time and request-level work; the slow log misses statements below its threshold.
- Interpret EXPLAIN in context: a scan or filesort is not automatically wrong.
- Explicit online DDL constraints fail when unsupported; they do not silently fall back.
- Treat pooling, caching, query rewrites, and locking as different problems with different fixes.
Turn on the slow query log: two variables, and one that gets forgotten
The MySQL slow query log records statements exceeding long_query_time that also satisfy the configured row-examination threshold. Inspect the current settings before enabling it:
SHOW VARIABLES LIKE 'slow_query_log';
SHOW VARIABLES LIKE 'long_query_time';
SHOW VARIABLES LIKE 'log_output';
SHOW VARIABLES LIKE 'slow_query_log_file';
SET GLOBAL log_output = 'FILE';
SET GLOBAL long_query_time = 1;
SET GLOBAL slow_query_log = 'ON';These settings can be changed dynamically with appropriate privileges. Verify the configured log path is writable and monitor disk usage; log_output=NONE produces no slow-query output. Runtime changes are not a persistence strategy: use your server configuration or managed-service settings for changes that must survive restarts.
What long_query_time to pick
Choose a threshold relative to your latency target and acceptable log volume. One second can be a starting point; 0.5 captures statements exceeding 500 ms, not 200 ms. Use a bounded diagnostic window and restore the intended production settings afterward.
long_query_time is session scoped, so SET GLOBAL hits only new sessions; pooled connections keep the old value until they reconnect.
SET SESSION long_query_time = 0.5;Managed MySQL: RDS and Cloud SQL
Use an RDS parameter group or Cloud SQL database flags for persistent configuration. Whether a change applies immediately or needs a restart depends on the parameter and service. Read the providerโs apply status and verify the effective SQL variables rather than assuming every change is pending reboot.
On RDS, set them in the parameter group, then list the log files the instance exposes:
aws rds describe-db-log-files \
--db-instance-identifier your-instance \
--region us-east-1 \
--query 'DescribeDBLogFiles[].LogFileName' \
--output textDo not hard-code the path: slowquery/mysql-slowquery.log is not reliable across replicas and clones, so take the name from that listing.
aws rds download-db-log-file-portion \
--db-instance-identifier your-instance \
--log-file-name '<log-file-name-from-listing>' \
--region us-east-1 \
--number-of-lines 5000 \
--output text --query 'LogFileData' > slow.logThis selects the log text from the response. The command retrieves a limited portion; account for pagination or export a complete diagnostic window before ranking workload totals.
Cloud SQL is the opposite trap: a flags patch replaces the whole list, so read it first and send it back merged.
gcloud sql instances describe your-instance \
--format='value(settings.databaseFlags)'When updating Cloud SQL flags, preserve the other flags you intend to keep. Use the console or construct a reviewed flags update from the current configuration; do not replace the full list with only the slow-log settings.
Read the resulting slow-query entries through the serviceโs logging interface. Validate collection and log volume on the intended instance; a read replica does not necessarily reproduce primary write traffic or lock contention.
Read what the log tells you: rank by total time, not single duration
Rank captured statements by cumulative execution time and frequency, not just the slowest individual call. A frequent 400 ms query can consume more database time than an occasional 30-second report. The threshold matters: statements faster than it will be absent from the slow log.
mysqldumpslow -s t -t 10 /var/log/mysql/slow.log # top 10 by total time
mysqldumpslow -s c -t 10 /var/log/mysql/slow.log # top 10 by count
mysqldumpslow -g 'JOIN' /var/log/mysql/slow.log # only JOINspt-query-digest groups by fingerprint, sorts by total time, and adds p95 and max beside the average.
pt-query-digest /var/log/mysql/slow.log
pt-query-digest --filter '$event->{Query_time} > 2' /var/log/mysql/slow.logA high count with a small average can indicate repeated application work, but does not prove N+1. Correlate it with request traces and Performance Schema digest statistics. Slow-log timing and Lock_time do not provide a complete picture of InnoDB row-lock waits; use the lock-wait views below.
Reading EXPLAIN in MySQL 8, without the folklore
In traditional EXPLAIN output, examine the access path, selected index, estimated row counts, and additional work. Interpret them together:
type:ALLmeans a full table scan. It can be appropriate for a small table or a query reading much of a table.key:NULLmeans no index was selected, not necessarily that no usable index exists.rows: an estimate, not an actual count. Compare estimates with execution evidence when safe.Extra:Using filesortindicates an additional sorting step, which need not use disk. Sorting and temporary tables are signals to investigate, not automatic defects.
One worked example
A support panel lists a customer’s newest orders:
EXPLAIN SELECT id, total, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;Suppose it reports type: ALL, key: NULL, and Using filesort. One cause: nothing indexed customer_id, so MySQL scanned and sorted.
A candidate index is (customer_id, created_at DESC). Check existing indexes, data distribution, and the full workload before building it. The controlled DDL example appears in the indexing section below.
After creating an appropriate index, re-run EXPLAIN and measure the query. MySQL can scan a B-tree index backward, so reversing the sort direction does not automatically reintroduce a filesort. Mixed column directions and predicates affect whether an index can satisfy ordering; see MySQL descending indexes.
Applying DATE() to a column can prevent a normal index from providing the desired range access. For this customer-specific query, retain the leading customer predicate and express the date interval as a half-open range:
SELECT id, total, created_at
FROM orders
WHERE customer_id = 42
AND created_at >= '2026-11-01'
AND created_at < '2026-11-02'
ORDER BY created_at DESC;A plain EXPLAIN SELECT shows the estimated plan without running that SELECT. EXPLAIN ANALYZE, available from MySQL 8.0.18, executes the statement to collect actual timing and row counts. Use a controlled environment or a carefully assessed production diagnostic window.
The five usual suspects behind slow MySQL queries
Choose the branch matching the evidence; these are common causes, not an exhaustive list or a guaranteed ranking.
| Suspect | Evidence to check | Next action |
|---|---|---|
| Index or query shape | Plan, examined rows, selectivity, existing indexes | Test a suitable index or semantics-preserving rewrite. |
| N+1 queries | Repeated statements within one request | Batch or eager-load the relationship in application code. |
| Connection pressure | Pool wait, active/idle connections, replica count | Budget all client pools and assess a compatible pooler. |
| Repeated reads | Repeated result requests and consistency needs | Evaluate caching and invalidation. |
| Lock contention | Blocking transactions and lock-wait views | Shorten transactions and review write ordering. |
1. Missing index
A large scan with selective predicates can indicate an indexing opportunity. Confirm using the plan and workload; an index is not necessarily beneficial when the query reads most rows.
SHOW INDEX FROM orders;
EXPLAIN SELECT id FROM orders WHERE customer_id = 42;Choose column order from the actual equality, range, ordering, and grouping requirements. Check for overlapping indexes, but do not assume every index sharing a leading column is redundant.
For supported InnoDB operations, explicit ALGORITHM=INPLACE, LOCK=NONE requests an online build that allows concurrent DML. It can still wait for metadata locks and consume I/O. Review the operation-specific restrictions first.
If MySQL cannot honor an explicitly requested algorithm or lock level, it returns an error. It does not silently downgrade this statement to a blocking COPY build. FULLTEXT and SPATIAL operations have their own restrictions; their presence is not a universal rule that every index addition requires COPY.
Check write volume and the online alteration log budget. Heavy concurrent changes can exhaust innodb_online_alter_log_max_size and fail an online index build.
SELECT @@innodb_online_alter_log_max_size;Inspect long-running transactions and replication health before starting. Metadata locks can delay the build, and online DDL can still create load or replication lag. Run this example only after reviewing the index and rollout plan:
ALTER TABLE orders
ADD INDEX idx_orders_customer_created (customer_id, created_at DESC),
ALGORITHM=INPLACE, LOCK=NONE;Monitor the operation and validate the resulting plan and latency. If the explicit algorithm or lock level is unsupported, investigate the error before selecting another strategy. Dropping an index later is another DDL operation, not an instant reversal of the buildโs operational cost.
An index fixes one query; the N+1 pattern creates many.
2. N+1 queries from the ORM
Filter to one fingerprint and compare counts across two runs.
pt-query-digest --filter '$event->{fingerprint} =~ /SELECT.*FROM order_items/i' \
--report-format profile /var/log/mysql/slow.logAn N+1 pattern loads a parent result set, then issues another query for each parent to fetch a relationship. A repeated fingerprint alone does not establish that relationship; inspect the application request or trace.
Fix the fetching strategy in application code. Depending on the relationship, options include Rails includes, Django select_related or prefetch_related, SQLAlchemy selectinload, and JPA JOIN FETCH. Preserve pagination and result semantics. See how to find and fix N+1 queries.
Once statement counts are controlled, check whether connection acquisition is adding latency independently.
3. No connection pooling
Compare application pool wait time with database connection counts and active work. Communication timeouts alone do not prove a pooling problem; network conditions and application behavior can produce similar symptoms.
SHOW STATUS LIKE 'Threads_connected';
SHOW STATUS LIKE 'Max_used_connections';
SHOW VARIABLES LIKE 'max_connections';
SELECT user, host, COUNT(*) AS conns
FROM information_schema.processlist
GROUP BY user, host
ORDER BY conns DESC;Read the actual max_connections value rather than sizing against a default. Raising it can increase resource pressure without improving useful concurrency.
In Kubernetes, each replica can open its own connection pool. Scaling from 6 to 40 pods can exceed max_connections if the combined pool budget is too large.
Budget the sum of pools across all replicas, workers, services, and database/user combinations, leaving room for administrative work and migrations. For example, 40 replicas with a maximum pool of three can open 120 connections before other clients are counted.
Align pool connection management with the serverโs idle timeout. Idle connections past wait_timeout can close, so a pool must validate or replace connections before reusing them.
Use the poolโs documented connection lifetime, idle validation, and keepalive settings to handle server-side idle expiry. An acquisition setting such as HikariCP connectionTimeout limits how long a client waits for a pool connection; it is not the connectionโs maximum lifetime.
A compatible pooler can reuse backend connections, subject to transaction and session-state constraints. ProxySQL is a MySQL option. For the PostgreSQL and managed-proxy trade-offs, see the connection pooling comparison. Cast AI uses ProxySQL for MySQL and PgDog for PostgreSQL.
With connections steady, the next suspect is the read itself: the same rows fetched again and again.

4. Repeated reads and caching
Measure whether applications repeat requests for the same results and whether those results can safely be reused. A normalized query fingerprint groups statements with different parameter values; high count alone does not prove cacheability.
MySQL 8.0 removed the old query result cache and its configuration options. InnoDBโs buffer pool still caches database pages. Do not attribute every upgrade regression to query-cache removal: compare plans, statistics, configuration, and workload behavior.
mysqld --defaults-file=/etc/my.cnf --validate-configOn versions supporting configuration validation, review its output for obsolete options before restarting. Evaluate application or proxy caching only with explicit freshness, invalidation, and transaction requirements. Caching does not repair an inefficient first execution or an applicationโs N+1 fetching pattern.
A cache handles repeated reads. It does nothing for two writers on the same row, the fifth suspect.
5. Lock contention
Investigate lock waits directly. The slow logโs Lock_time is not a complete measure of InnoDB transaction lock contention.
For MySQL 8.0/8.4, start with the sys view and inspect Performance Schema when you need the waiting and blocking identifiers:
SELECT * FROM sys.innodb_lock_waits;SELECT
w.REQUESTING_ENGINE_TRANSACTION_ID AS waiting_trx,
w.REQUESTING_THREAD_ID AS waiting_thread,
w.BLOCKING_ENGINE_TRANSACTION_ID AS blocking_trx,
w.BLOCKING_THREAD_ID AS blocking_thread
FROM performance_schema.data_lock_waits w;Raw IDs tell you who waits. Sort by age to find the holders, not the statement that waited.
SELECT trx_id, trx_mysql_thread_id,
TIMESTAMPDIFF(SECOND, trx_started, NOW()) AS age_sec,
trx_rows_locked, trx_query
FROM information_schema.innodb_trx
ORDER BY age_sec DESC
LIMIT 10;DDL also needs metadata locks and can queue behind open transactions. Inspect performance_schema.metadata_locks alongside transaction details. SHOW ENGINE INNODB STATUS provides additional InnoDB diagnostic information; it is not a complete history of every blocker.
Reduce long transactions and unnecessary work inside them. Consistent write ordering can reduce deadlock risk. Adjusting a timeout changes how long a session waits; it does not remove the underlying contention.
Correlate query evidence with memory and storage activity. IOPS counts alone do not prove saturation; compare storage latency, throughput, and provisioned limits over the same period.

What automation adds to the loop
Cast AI Database Optimizer helps turn recurring diagnosis into a prioritized workflow. Its Performance Advisor analyzes query statistics and metadata with read-only access, then recommends index or query changes for review. It does not execute DDL. Plan comparisons and projected improvements are evidence to validate, not measured savings or a guarantee.
Optional proxy capabilities add connection pooling and caching for suitable workloads. They do not automatically change ORM fetching, shorten application transactions, or eliminate every lock wait. For ongoing measurement, see database observability; for the PostgreSQL workflow, see finding slow PostgreSQL queries.
Conclusion
Capture a representative workload, rank cumulative query time, inspect plans, and follow the evidence to indexes, application fetching, connections, caching, or locks. Validate each change against latency, resource use, errors, and replication health before expanding it.
Frequently asked questions
Inspect slow_query_log, long_query_time, log_output, and the log path. With suitable privileges, enable slow_query_log and choose a threshold and output destination. Persist the intended settings through server configuration or your managed service, and verify log volume.
Choose it against your latency objective and log budget. A one-second threshold can be a starting point; 0.5 captures statements slower than 500 ms. Global changes to this session variable affect new sessions, so existing pooled connections need separate consideration.
Read the access type, chosen key, estimated rows, and Extra together. ALL is a scan, key NULL means no index was selected, and Using filesort means an additional sort. None alone proves a defect. EXPLAIN ANALYZE executes the statement to collect actual evidence.
Compare query plans, statistics, settings, and workload changes. MySQL 8.0 removed the old query result cache, but the InnoDB buffer pool remains. Obsolete configuration options can prevent startup; that is different from a query-performance regression.
No. Performance Advisor uses read-only access and provides recommendations for review; you control applying SQL or DDL. Optional caching and connection pooling can reduce suitable database work, but do not fix application fetching or transaction logic automatically.



