How to find and fix slow MySQL queries for developers
To find and fix slow MySQL queries, identify the statements causing delays, inspect their execution plans with EXPLAIN or EXPLAIN ANALYZE, and optimize the operations responsible for excessive processing. Common fixes include adding suitable indexes, reducing unnecessary row scans, and improving JOIN or filtering conditions. Diagnose the query first instead of optimizing by trial and error.
In our MySQL 8.0.34 test with 1.6 million payment records, adding a covering index reduced query execution time from 4.296 seconds to 0.838 seconds, an 80.5% reduction. This guide demonstrates the process using native MySQL tools and the Query Profiler in dbForge Studio for MySQL.
The workflow has seven steps: identify the query, collect baseline performance data, inspect the execution plan, determine why MySQL processes the query slowly, modify the query or the indexes, run the query again, and compare the results. MySQL provides the slow query log, EXPLAIN, and EXPLAIN ANALYZE for this. dbForge Studio for MySQL, a MySQL database IDE, adds visual query analysis with Query Profiler, a MySQL profiler tool.
Summary
- Find slow statements with the slow query log, ranked by time and rows examined.
- Read EXPLAIN and EXPLAIN ANALYZE to see why MySQL does so much work.
- Fix the bottleneck the plan shows: an index, less data, or a simpler query structure.
- Measure before and after, so you can prove the improvement.
What makes a MySQL query slow?
A MySQL query can be slow on a large table because it processes too much data, uses an inefficient execution plan, or waits on resource contention. Most causes are visible at the query level:
- Missing or unsuitable indexes, which lead to full table scans.
- Low-selectivity filters that force MySQL to scan and examine many rows.
- Inefficient JOIN conditions and large intermediate results.
- Unnecessary data retrieval: extra columns or rows the application never uses.
- Expensive sorting and grouping, often through temporary tables.
- Complex or poorly structured subqueries.
- Outdated statistics or inaccurate optimizer estimates, which lead to a poor plan.
- Locking and contention between concurrent statements.
- Queries that worked on a small dataset but slowed down as data volume grew.
Do not assume which of these applies. Confirm the cause with measurements and the execution plan before you change anything.
How to find slow queries in MySQL
To find and monitor slow queries, identify the SQL statements responsible for application latency. You may already know the problem query from application monitoring or testing. Otherwise, use the MySQL slow query log to detect and show slow running queries as candidates.
The goal is not just to find a query that takes a long time. Pick statements worth investigating by execution time, frequency, and the amount of data they process.
The examples in this guide use a copy of the Sakila sample database with about 1.6 million rows in the payment and rental tables. The standard Sakila database has only about 16,000 of each, which is too small to show a difference. We generated the extra rows by replicating the existing records and spreading their dates over 2022-2025. All measurements come from MySQL 8.0.34, so the behavior of other MySQL versions and of MariaDB may differ.
Check the MySQL slow query log
The slow query log records statements that exceed the long_query_time threshold and meet the other logging criteria you configure. Use it when you do not know which query causes the delay. To check the current configuration, run:
SHOW VARIABLES LIKE 'slow_query_log';
SHOW VARIABLES LIKE 'long_query_time';
SHOW VARIABLES LIKE 'slow_query_log_file';
The main variables are:
- slow_query_log: turns the log on or off.
- slow_query_log_file: the path to the log file.
- long_query_time: the time in seconds above which a statement is logged.
- min_examined_row_limit: skips statements that examine fewer rows than the limit.
- log_queries_not_using_indexes: also logs statements that do not use an index.
Do not treat the default long_query_time as the right value for every application. Set the threshold based on your application's latency requirements and workload. For detailed configuration instructions, see the MySQL slow query log documentation.
Read and prioritize slow query log entries
In each log entry, check four values first: Query_time, Lock_time, Rows_examined, and Rows_sent. A query that examines millions of rows but sends only a few usually has an indexing or filtering problem.
Use mysqldumpslow, which ships with MySQL, to group similar statements and sort them by query time (-s t), by count (-s c), or by average query time (-s at):
mysqldumpslow -s t -t 10 /var/lib/mysql/slow-query.log
Check both rankings: a fast statement that runs very often can cost more than a rare slow one. Take the top statements from the summary and analyze them one by one with EXPLAIN.
Analyze slow MySQL queries with EXPLAIN and EXPLAIN ANALYZE
To analyze a slow MySQL query, prefix it with EXPLAIN to see the optimizer's plan, or with EXPLAIN ANALYZE to also run it and measure actual execution. Look for full table scans, high row counts, temporary tables, and sorting.
The slow query log shows the symptom, and the execution plan helps identify inefficient operations and potential bottlenecks. MySQL has two commands for it, with different behavior:
EXPLAINshows the plan the optimizer chose without executing a SELECT query.EXPLAIN ANALYZEexecutes the statement and adds actual execution measurements: actual execution time, actual rows, and loop counts.
Use EXPLAIN ANALYZE carefully, because MySQL really runs the statement. It is available in MySQL 8.0.18 and later. See the EXPLAIN statement documentation for details.
The rest of this guide uses one query: revenue by film category for one quarter. Prefix the query with EXPLAIN or EXPLAIN ANALYZE to get the plan:
SELECT c.name AS category, COUNT(*) AS payments, SUM(p.amount) AS revenue
FROM payment p
JOIN rental r ON r.rental_id = p.rental_id
JOIN inventory i ON i.inventory_id = r.inventory_id
JOIN film_category fc ON fc.film_id = i.film_id
JOIN category c ON c.category_id = fc.category_id
WHERE p.payment_date >= '2025-04-01' AND p.payment_date < '2025-07-01'
GROUP BY c.category_id, c.name
ORDER BY revenue DESC;
On our test data, EXPLAIN ANALYZE shows that MySQL reads all 1.6 million payment rows to keep about 100,000 of them:
-> Filter: (p.payment_date >= '2025-04-01' and p.payment_date < '2025-07-01' and p.rental_id is not null)
(cost=163332 rows=177750) (actual time=0.314..909 rows=99997 loops=1)
-> Table scan on p (cost=163332 rows=1.6e+6) (actual time=0.308..752 rows=1.6e+6 loops=1)
What to look for in a MySQL execution plan
Do not read every plan column in isolation. Look for signals that show where MySQL does unnecessary work: the access type, possible and selected indexes, estimated and actual rows, filtering, JOIN order, temporary tables, and sorting. The same signal can have different names in different output formats. For example, a full table scan is type: ALL in traditional EXPLAIN output and Table scan in the tree format that EXPLAIN ANALYZE uses. The table shows what each signal may mean and what to check next.
| Signal | Possible problem | What to check |
|---|---|---|
Full table scan (type: ALL in EXPLAIN, Table scan in EXPLAIN ANALYZE) |
Missing or unusable index | WHERE and JOIN columns |
| Very high rows examined | Too much data processed | Filters and indexes |
| Relevant index not selected | Index design or optimizer estimate issue | Index structure and statistics |
| Expensive JOIN | Large intermediate result | JOIN conditions and indexes |
| Temporary processing or sorting | ORDER BY or GROUP BY overhead | Query structure and index order |
| Large difference between estimated and actual rows | Cardinality estimation issue | Statistics and data distribution |
In our plan, the full scan of payment is the main signal. The optimizer also estimated about 177,750 rows after filtering, while the actual count was 99,997.
How to fix slow MySQL queries
The best way to fix a slow MySQL query is to examine its execution plan to identify inefficient operations. Depending on the bottleneck, you may need to add or modify an index, reduce unnecessary data retrieval, improve JOIN conditions, or optimize sorting and aggregation. Measure query performance before and after each change to verify the improvement. Do not apply random rewrites or add indexes before the diagnosis.
Add or improve indexes
An index helps when it matches the columns a query uses in WHERE, JOIN, and ORDER BY, or in repeated lookups. Check the execution plan before and after you add it.
More indexes are not automatically better. An index can speed up reads, but it uses storage and adds overhead to every INSERT, UPDATE, and DELETE. In our example, the filter on payment_date has no index, so MySQL scans the whole table. A composite index fixes this. Step 3 below creates it.
Creating an index on a large production table consumes I/O, CPU, and storage, and it can affect concurrent workloads. Test index changes against a representative workload before you deploy them.
Reduce the amount of data MySQL processes
Many slow queries read or return much more data than the application needs. To reduce it:
- Return only the columns you need.
- Apply selective filters as early as possible.
- Avoid fetching large result sets; use pagination where appropriate.
- Check filters that prevent MySQL from using an index, such as a function applied to an indexed column.
SELECT * is not always slow. Its cost depends on table width, index coverage, result size, and network transfer, so measure it in context.
Review JOINs, subqueries, sorting, and aggregation
A complex query structure can make MySQL do more work than necessary. JOINs and subqueries are not slow by themselves. Look for incorrect or incomplete JOIN conditions, missing indexes on JOIN keys, unnecessary JOINs, and large intermediate result sets.
Also check repeated calculations, expensive ORDER BY and GROUP BY operations, and unnecessarily nested queries. The goal is to reduce unnecessary processing while keeping the result identical.
When to use MySQL tools vs. dbForge Query Profiler
MySQL's built-in tools for monitoring slow queries and dbForge Query Profiler serve different purposes in query performance analysis. The slow query log helps identify problematic SQL statements, while EXPLAIN and EXPLAIN ANALYZE reveal how MySQL executes them. These tools are useful for diagnosing individual queries and investigating performance issues without additional software.
dbForge Query Profiler builds on this analysis by providing a visual workflow for examining and optimizing SQL queries. It brings execution plans, profiling statistics, and historical results into one interface, making it easier to identify bottlenecks and evaluate changes.
| Task | Recommended tool |
|---|---|
| Find slow queries across a database workload | MySQL slow query log |
| Identify frequently occurring or expensive statements | mysqldumpslow |
| Check index usage and estimated execution plans | MySQL EXPLAIN |
| Measure actual execution plan operations | MySQL EXPLAIN ANALYZE |
| Analyze execution plans visually | dbForge Query Profiler |
| Review execution-related session statistics | dbForge Query Profiler |
| Compare query performance before and after optimization | dbForge Query Profiler |
Which should you choose? Use MySQL's native tools to identify slow statements and investigate their execution plans. Choose dbForge Query Profiler when you need visual plan analysis, profiling history, and convenient before-and-after comparisons within a single IDE. The tools complement each other rather than replace one another.
How to find and fix slow queries with dbForge Studio for MySQL
With Query Profiler in dbForge Studio for MySQL, you can profile a query, review its execution plan, and check the fix in one window. Query Profiler provides:
- Query profiling and execution plan review.
- A visual EXPLAIN tree.
- Session statistics for the current connection.
- Profiling history, so you can return to earlier versions of a query.
- Comparison of profiling results before and after changes.
The walkthrough reuses the query from the previous sections, so you can see the same plan visually.
dbForge Studio for MySQL
A powerful, all-in-one IDE for MySQL and MariaDB professionals that helps design, develop, manage, and optimize databases faster and with confidence.
Step 1. Profile the slow MySQL query
Open the problem query in SQL Editor and run it with Query Profiler. This is your baseline: record it before you change the SQL or the indexes. The Profile tab breaks the run down by state. In our baseline run, 4.295 s of the 4.296 s total (99.98%) is spent in the executing state, so most of the recorded time is attributed to query execution rather than to the other measured states. The Plan, Plan Diagram, and Session statistics tabs show the execution plan and the server counters for the run.
Step 2. Analyze the visual EXPLAIN tree
The visual EXPLAIN tree shows the query execution hierarchy, so complex plans are easier to inspect than a table of columns. Each node is a separate operation. Check the execution order, table access, JOIN processing, nested operations, table scans, index usage, and filtering.
To open it, run the query in Query Profiler and select Plan Diagram. In our query, three nodes show where the work goes:
- Table Scan p (Full) reads the whole payment table, and the date filter is applied only after the rows are read.
- Group (Temporary Table) aggregates the rows through a temporary table.
- File Sort sorts the 16 grouped rows, so sorting has little impact in this example.
The other nodes are Row Lookup operations on unique keys. They are not the bottleneck.
Step 3. Fix the query or index
Apply the change the diagnosis suggests. Depending on the plan, this can be a new or modified index, a rewritten filter, less retrieved data, a changed JOIN, or less sorting and aggregation. Here, the date filter needs an index, so create a composite index. It starts with payment_date and also includes rental_id and amount, the other payment columns the query reads:
CREATE INDEX idx_payment_date_rental_amount
ON payment (payment_date, rental_id, amount);
MySQL can then read the matching rows from the index range instead of scanning the table. Because the index contains every payment column the query uses, it is a covering index: MySQL can retrieve the required columns without additional table-row lookups.
Run the query again and open Plan Diagram. The Table Scan p (Full) node is now Index Scan p (Range).
Step 4. Compare query performance before and after optimization
Run the optimized query again and compare the two profiling results in Query Profiler. Compare measurements, not impressions. Here are the results of our test on MySQL 8.0.34 with 1.6 million payments. The "after" time is a warm run. Cache warming can affect the first execution after an index change, so run the query several times and compare warm runs under comparable conditions.
Test environment and methodology
The optimization was tested on MySQL 8.0.34 with default server settings, including a 128 MB InnoDB buffer pool, using an expanded Sakila sample database with about 1.6 million payment records. Both versions of the query returned identical results.
Execution time was measured in Query Profiler. The baseline is the first run of the original query. The optimized value is the lower of two warm runs (0.859 s and 0.838 s). The first run after creating the index was slower because of cache warming and is not included. The execution plans were also checked with EXPLAIN ANALYZE. Actual performance improvements depend on data distribution, hardware, server configuration, and workload.
| Metric | Before optimization | After optimization |
|---|---|---|
| Execution time in Query Profiler | 4.296 s | 0.838 s |
| Rows read from payment | About 1.6 million | 99,997 |
Rows read by table scan (Handler_read_rnd_next in session statistics) |
1,604,417 | 17 |
| Time to read the matching payment rows | 909 ms | 97 ms |
| Index usage | None (ALL) |
Covering index range scan (range) |
| Execution plan | Full table scan, temporary table, filesort | Index range scan, temporary table, filesort |
Query optimization result
In our test with 1.6 million payment records (Sakila database), adding a covering index reduced query execution time from 4.296 seconds to 0.838 seconds.
The metrics come from different tools and from separate executions of the same query on the same data. Execution time and session statistics come from Query Profiler. The rows read from payment and the time to read them come from EXPLAIN ANALYZE, whose per-step timing adds overhead, so use them to compare steps rather than as total query time. The 99,997 rows after optimization are the rows read through the index range, not the 16 rows of the final result.
Query Profiler also shows the plan diagrams of the two runs one above the other. The baseline plan (top) contains Table Scan p (Full), and the optimized plan (bottom) contains Index Scan p (Range). The estimated total cost is reported as greater than 416,560.61 before the change and greater than 304,767.9 after it.
The Session statistics tab shows how the server status variables changed during each run. Handler_read_rnd_next counts requests to read the next row in the data file, which is what a table scan does. It drops from 1,604,417 for the baseline run to 17 for the optimized one.
Example: fixing a slow MySQL query step by step
The query was slow because payment_date had no index, so MySQL scanned all 1.6 million rows of payment to find the 99,997 rows from one quarter. The covering index on payment_date, rental_id, and amount lets MySQL read only those rows from the index range, without additional table-row lookups. The remaining time goes mostly to the lookups in rental, so further optimization would start there. This is why you measure instead of assuming.
Slow MySQL query troubleshooting checklist
These best practices to fix slow queries in MySQL cover the steps in this guide, from finding the statement to verifying the fix:
- Confirm that the slowdown is caused by a database query.
- Identify the problem SQL statement.
- Record baseline performance.
- Check the slow query log when appropriate.
- Run
EXPLAIN. - Use
EXPLAIN ANALYZEwhen actual execution measurements are required and safe. - Check how many rows MySQL processes.
- Check table scans and index usage.
- Review WHERE conditions.
- Review JOIN conditions.
- Check ORDER BY and GROUP BY operations.
- Review indexes.
- Apply one meaningful change at a time.
- Profile the query again.
- Compare performance before and after.
- Validate the change with realistic data volumes.
Do not consider a query optimized until the improvement has been measured.
Why use dbForge Studio for MySQL for slow query analysis?
dbForge Studio for MySQL brings SQL editing, query profiling, visual execution plans, and performance comparison into one IDE. Developers can inspect expensive operations, test query or index changes, and compare profiling results without switching between separate tools.
| Task | How dbForge Studio for MySQL helps |
|---|---|
| Identify expensive operations | The visual EXPLAIN tree shows table scans, index access, JOINs, sorting, and aggregation. |
| Examine execution behavior | Query Profiler shows execution details and session statistics. |
| Test an optimization | SQL Editor lets you apply changes and rerun the query. |
| Compare results | Profiling history supports before-and-after analysis. |
| Investigate possible improvements | AI Assistant can help with SQL troubleshooting and query optimization. |
Treat the AI Assistant as a complement to execution plan analysis, not a replacement for it.
Try dbForge Studio for MySQL on your own slow queries with the free trial.
Final thoughts
Fixing a slow query takes four steps: find the statement with the slow query log, analyze it with EXPLAIN and EXPLAIN ANALYZE, fix the bottleneck you diagnosed, and measure the result instead of relying on assumptions. If you prefer to do this visually, dbForge Studio for MySQL combines query profiling, execution plan analysis, and before-and-after comparison in one IDE. You can download dbForge Studio for MySQL and try it on your own queries.
FAQ
Enable the slow query log and set long_query_time to a threshold that matches your latency requirements. MySQL then writes the statements that exceed the threshold and meet the other logging criteria to the log file, together with query time, lock time, rows sent, and rows examined. Summarize the log with mysqldumpslow, then investigate the statements that rank highest by query time or count, or that examine the most rows.
Run EXPLAIN to find out why MySQL processes the query slowly, then change only what the plan points to. Typical fixes are adding or adjusting an index, returning fewer rows and columns, or simplifying JOINs, sorting, and aggregation. Run the query again and compare the measured results with the baseline.
Put EXPLAIN in front of the SELECT statement and read the access type, the selected index, the estimated rows, and the Extra column. A full table scan (type ALL), a very high rows estimate, or Using temporary and Using filesort in Extra can show where the work goes, depending on how much data is processed. Check the WHERE and JOIN columns and the indexes on them next.
EXPLAIN shows the execution plan the optimizer chose without running a SELECT statement. EXPLAIN ANALYZE, available in MySQL 8.0.18 and later, runs the statement and adds actual time, actual rows, and loop counts for each plan step. Use it carefully, because the statement is really executed.
Look at the key column in the EXPLAIN output: it shows the index MySQL selected, and NULL means no index is used. The type column shows how the table is accessed. ALL means a full table scan, while ref, range, and eq_ref mean an index is used. The possible_keys column lists indexes the optimizer considered.
Measure the query before the change and run the identical query again afterwards, on the same data. Compare execution time, the number of rows processed, index usage, and the structure of the execution plan. In dbForge Studio for MySQL, Query Profiler keeps previous profiling results and compares them side by side.
Yes. Query Profiler in dbForge Studio for MySQL profiles a query, shows its execution plan as a visual EXPLAIN tree, and displays session statistics. Profiling history and result comparison let you check an optimization against the original run. To find slow statements in the first place, you can still use the MySQL slow query log.