How to Fix Slow MySQL Queries is essential for improving database performance, website speed, and user experience. Slow MySQL queries can increase server load, delay page rendering, slow reports, and negatively impact application performance. In many cases, the root cause is inefficient SQL statements, missing indexes, poor schema design, or incorrect database configuration.
In this guide, you’ll learn How to Fix Slow MySQL Queries using 16 proven optimization techniques, including slow query logs, EXPLAIN, indexing, query optimization, caching, pagination improvements, and MySQL server tuning to boost database performance in 2026.
Check Your MySQL Version First
Before learning How to Fix Slow MySQL Queries, start by checking your MySQL version. Different versions include different optimization features, indexing capabilities, and query execution improvements.
SELECT VERSION();
MySQL 5.7, 8.0, 8.4, and newer versions may use different optimizer behavior, indexing features, and execution plan improvements. For example, MySQL 8.0+ supports features such as invisible indexes, descending indexes, histograms, and EXPLAIN ANALYZE.
What Are Slow MySQL Queries?
Slow MySQL queries are SQL statements that take longer than expected to execute. A query may be slow because it scans too many rows, uses no index, joins large tables inefficiently, sorts too much data, locks rows, or returns more results than needed.
Understanding what causes slow queries is the first step in learning How to Fix Slow MySQL Queries effectively. MySQL provides several built-in tools to identify and analyze performance bottlenecks, including the Slow Query Log, EXPLAIN, EXPLAIN ANALYZE, and Performance Schema. These tools help developers determine why queries are slow and what optimizations are needed. For example, the Slow Query Log records queries that exceed the configured long_query_time threshold, while tools such as mysqldumpslow can summarize and analyze the collected data.
Why Slow MySQL Queries Happen
Understanding why queries become slow is essential when learning How to Fix Slow MySQL Queries. In most cases, poor performance is caused by inefficient query design, missing indexes, outdated database statistics, or configuration issues that force MySQL to process more data than necessary.
Common causes of slow MySQL queries include:
- Missing indexes
- Wrong index order
- Too many full table scans
- Using
SELECT * - Poor JOIN conditions
- Large OFFSET pagination
- Unoptimized subqueries
- Outdated statistics
- Large unarchived tables
- Locking and transaction issues
- Weak server configuration
Quick Checklist to Fix Slow MySQL Queries
Once you’ve identified the root cause, use the checklist below as a quick reference for How to Fix Slow MySQL Queries efficiently.
| Problem | Quick Fix |
|---|---|
| Full table scan | Add a proper index |
| Slow JOIN | Index join columns |
| Too much data returned | Select only needed columns |
| Slow pagination | Use keyset pagination |
| Slow reports | Add summary tables or caching |
| High CPU | Optimize queries and indexes |
| Lock waits | Keep transactions short |
| Slow writes | Avoid too many unnecessary indexes |
Signs Your MySQL Queries Are Slow

Many developers first notice database problems only after traffic spikes or customer complaints begin appearing. In production environments, even one poorly optimized query can gradually slow down an entire application.
Before learning how to fix slow MySQL queries, it helps to recognize the warning signs.
You may have slow MySQL queries if:
- Pages take more than 2–3 seconds to load
- CPU usage remains consistently high
- Database connections keep increasing
- Dashboard reports run slowly
- API responses become delayed
- Users experience timeout errors
- Search functionality feels sluggish
- Database servers require frequent restarts
- Background jobs take longer than expected
- Peak traffic causes performance degradation
These symptoms often indicate inefficient query execution rather than insufficient server resources. Identifying these issues early makes it easier to understand how to fix slow MySQL queries before they affect users and business operations.
1. Enable the MySQL Slow Query Log
The first step in learning how to fix slow MySQL queries is finding which queries are actually slow. Do not guess. Use the slow query log.
Example:
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
SET GLOBAL log_queries_not_using_indexes = 'ON';
This helps you capture queries that take longer than your chosen threshold. For production websites, choose a sensible value such as 0.5, 1, or 2 seconds depending on your workload.
You can summarize slow logs using:
mysqldumpslow -s t -t 10 /var/log/mysql/mysql-slow.log
This command displays the slowest and most frequently executed queries, making it easier to determine How to Fix Slow MySQL Queries based on real performance data rather than assumptions.
Use Performance Schema Statement Digests
While the Slow Query Log identifies individual slow statements, Performance Schema Statement Digests helps you analyze query patterns across your entire workload. This is especially useful when learning How to Fix Slow MySQL Queries because some queries may not appear slow individually but become expensive when executed thousands of times.
Example:
SELECT DIGEST_TEXT, COUNT_STAR, AVG_TIMER_WAIT, SUM_TIMER_WAIT FROM performance_schema.events_statements_summary_by_digest ORDER BY SUM_TIMER_WAIT DESC LIMIT 10;
2. Use EXPLAIN Before Changing Queries
EXPLAIN shows how MySQL plans to execute a query, including table access order, index usage, estimated rows, and join strategy. MySQL documentation recommends EXPLAIN for understanding query execution plans.
Example:
EXPLAIN SELECT * FROM orders WHERE customer_id = 25;
Look for warning signs such as:
type = ALL- High
rowscount Using temporaryUsing filesort- Missing index in the
keycolumn
These indicators often reveal why a query is slow and what changes are needed. Understanding execution plans is a critical skill when learning How to Fix Slow MySQL Queries and improve overall database efficiency.
3. Use EXPLAIN ANALYZE for Real Execution Data
EXPLAIN estimates the plan, while EXPLAIN ANALYZE actually runs the query and reports execution details. MySQL uses TREE format for EXPLAIN ANALYZE, which provides more precise plan information.
Example:
EXPLAIN ANALYZE
SELECT customer_id, SUM(total)
FROM orders
WHERE created_at >= '2026-01-01'
GROUP BY customer_id;
Use it to compare expected rows vs actual rows. If MySQL’s estimate is far from reality, statistics or indexes may need attention.
4. Add Indexes to WHERE Columns
Indexes are one of the most effective ways to learn How to Fix Slow MySQL Queries because they help MySQL find matching rows faster instead of scanning an entire table. When a query filters data using a WHERE condition, adding an index to that column can greatly improve SELECT performance.
Slow query:
SELECT * FROM users WHERE email = 'user@example.com';
Fix:
CREATE INDEX idx_users_email ON users(email);
Best columns to index:
- Columns used in
WHERE - Columns used in
JOIN - Columns used in
ORDER BY - Columns used in
GROUP BY - Frequently searched columns
Do not index every column. Too many indexes slow down inserts, updates, and deletes.
Test Index Changes With Invisible Indexes
Invisible indexes are useful when you want to test whether an index is still needed without dropping it immediately. This is a safer method when deciding How to Fix Slow MySQL Queries without risking sudden performance issues.
ALTER TABLE orders ALTER INDEX idx_old_status INVISIBLE;
If performance stays healthy, you can later drop the index. If performance gets worse, make it visible again:
ALTER TABLE orders ALTER INDEX idx_old_status VISIBLE;
5. Use Composite Indexes Correctly
A composite index includes more than one column and can improve queries that filter, sort, or group data using multiple fields. Using composite indexes correctly is an important part of How to Fix Slow MySQL Queries, especially for large tables and high-traffic applications.
Example:
CREATE INDEX idx_orders_customer_date
ON orders(customer_id, created_at);
This helps queries like:
SELECT *
FROM orders
WHERE customer_id = 10
ORDER BY created_at DESC;
Use Descending Indexes for Newer MySQL Versions
If your query frequently sorts newest records first, a descending index can help.
CREATE INDEX idx_orders_customer_created_desc ON orders(customer_id, created_at DESC);
This is useful for queries like:
SELECT id, total, created_at FROM orders WHERE customer_id = 25 ORDER BY created_at DESC LIMIT 10;
Descending indexes can improve queries where the best scan order is descending or mixed ASC/DESC.
Optimize Data Types
Using oversized data types can increase storage requirements and reduce query performance.
Examples:
- Use
INTinstead ofBIGINTwhen the range is enough - Use
VARCHAR(100)instead ofVARCHAR(1000)when appropriate - Use
DATEinstead ofDATETIMEif time values are unnecessary - Avoid storing numeric values as strings
Choosing the right data types is a simple but powerful step in How to Fix Slow MySQL Queries because smaller indexes are usually faster to scan and easier to cache in memory.
6. Avoid SELECT *
Using SELECT * forces MySQL to return every column, even when your application only needs a few. This increases disk reads, memory usage, network transfer, and response time.
Bad:
SELECT * FROM products WHERE category_id = 5;
Better:
SELECT id, name, price, stock_status
FROM products
WHERE category_id = 5;
This is especially important for tables with large text, JSON, image paths, logs, or metadata columns.
7. Replace Large OFFSET Pagination
This issue commonly appears in large eCommerce stores, forums, analytics dashboards, and social media platforms where users browse deeply paginated content.
Large OFFSET pagination becomes slower as users move deeper into results.
Slow:
SELECT id, title
FROM posts
ORDER BY id DESC
LIMIT 20 OFFSET 100000;
Better keyset pagination:
SELECT id, title
FROM posts
WHERE id < 500000
ORDER BY id DESC
LIMIT 20;
This avoids scanning and skipping thousands of rows.
When learning How to Fix Slow MySQL Queries, replacing large OFFSET pagination with keyset pagination is one of the most effective ways to improve performance on large datasets.
8. Rewrite OR Conditions
Queries with many OR conditions may prevent efficient index use.
Slow:
SELECT *
FROM users
WHERE email = 'a@example.com' OR phone = '1234567890';
Better:
SELECT *
FROM users
WHERE email = 'a@example.com'
UNION
SELECT *
FROM users
WHERE phone = '1234567890';
Then add indexes:
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_phone ON users(phone);
Query rewrites are often overlooked, but they can play a major role in How to Fix Slow MySQL Queries by helping MySQL use indexes more efficiently.
9. Avoid Functions on Indexed Columns
Using functions on indexed columns can stop MySQL from using the index efficiently.
Slow:
SELECT *
FROM orders
WHERE DATE(created_at) = '2026-05-01';
Better:
SELECT *
FROM orders
WHERE created_at >= '2026-05-01'
AND created_at < '2026-05-02';
This allows MySQL to use an index on created_at.
10. Optimize GROUP BY and ORDER BY
GROUP BY and ORDER BY can be expensive on large tables. If MySQL shows Using temporary or Using filesort, consider adding a matching index.
Example:
CREATE INDEX idx_orders_status_created
ON orders(status, created_at);
Useful for:
SELECT status, COUNT(*)
FROM orders
WHERE created_at >= '2026-01-01'
GROUP BY status;
Efficient sorting and aggregation strategies are essential for How to Fix Slow MySQL Queries, especially in reporting and analytics workloads.
11. Keep Table Statistics Updated
MySQL uses optimizer statistics to choose query plans. If statistics are outdated, MySQL may choose a poor plan.
Use:
ANALYZE TABLE orders;
This is useful after large imports, deletes, updates, or major data changes.
Use Histograms for Columns With Uneven Data
Sometimes MySQL chooses a poor plan because it does not understand how data is distributed. Histograms help the optimizer estimate selectivity more accurately, especially when a column has uneven values.
Example:
ANALYZE TABLE orders UPDATE HISTOGRAM ON status;
This can help when a column has values like pending, paid, cancelled, and one value is much more common than others.
12. Use Covering Indexes
A covering index includes all columns needed by the query, so MySQL can read from the index without accessing the full table.
Example:
CREATE INDEX idx_orders_cover
ON orders(customer_id, created_at, total);
Query:
SELECT created_at, total
FROM orders
WHERE customer_id = 10;
This can greatly reduce disk reads.
Covering indexes are considered one of the most effective techniques for How to Fix Slow MySQL Queries because they reduce unnecessary table lookups.
13. Archive Old Data
Large tables become harder to scan, sort, back up, and maintain. If your application keeps years of logs, sessions, orders, or analytics data, archive old records.
Options:
- Move old rows to archive tables
- Partition large time-based tables
- Delete expired logs
- Store analytics summaries
- Use cold storage for historical data
For example, instead of querying 100 million log rows, create daily or monthly summary tables.
Consider Table Partitioning for Massive Tables
If your database contains millions or billions of rows, table partitioning can significantly improve performance and maintenance operations.
Partitioning divides a large table into smaller logical sections while allowing applications to query it as a single table.
Common use cases include:
- Log tables
- Analytics databases
- Order history
- Event tracking systems
- Time-series applications
- IoT platforms
- Financial transaction records
Benefits of partitioning:
- Faster data management
- Improved maintenance operations
- Easier archival processes
- Better query performance for date-based searches
- Reduced index sizes
Example:
CREATE TABLE orders (
id BIGINT,
order_date DATE,
customer_id INT
)
PARTITION BY RANGE (YEAR(order_date)) (
PARTITION p2024 VALUES LESS THAN (2025),
PARTITION p2025 VALUES LESS THAN (2026),
PARTITION p2026 VALUES LESS THAN (2027)
);
For large datasets, partitioning is one of the most overlooked techniques when learning how to fix slow MySQL queries at scale.
14. Use Caching for Repeated Queries
Some queries should not hit MySQL every time. Cache repeated, expensive, or read-heavy results.
Good caching targets:
- Homepage widgets
- Popular posts
- Product category counts
- Dashboard metrics
- Reports
- Search filters
- User permissions
Common caching tools include Redis, Memcached, CDN cache, application cache, and materialized summary tables.
Caching is often a critical component of How to Fix Slow MySQL Queries because it reduces the number of database requests that need to be processed.
15. Tune MySQL Server Configuration
Query optimization should come first, but server settings also matter.
Important MySQL settings include:
innodb_buffer_pool_sizemax_connectionstmp_table_sizemax_heap_table_sizesort_buffer_sizejoin_buffer_sizeinnodb_flush_log_at_trx_commit
For InnoDB-heavy workloads, the buffer pool is especially important because it stores cached data and indexes in memory.
Server tuning becomes important after query optimization and indexing have been addressed when determining How to Fix Slow MySQL Queries at scale.
Reduce Locking and Long Transactions
Not all performance problems are caused by inefficient SQL queries. In many cases, slow response times occur because queries are waiting for locks to be released. Understanding lock contention is an important part of How to Fix Slow MySQL Queries, especially in high-traffic applications that process frequent updates and transactions.
Common Causes of Lock Contention
- Long-running transactions that keep rows locked for extended periods
- Large UPDATE or DELETE operations affecting thousands of rows
- Uncommitted transactions that hold locks unnecessarily
- Excessive row-level locking during peak workloads
- Concurrent processes competing for the same data
Best Practices to Reduce Locking
- Keep transactions as short as possible
- Commit or roll back transactions promptly
- Break large updates into smaller batches
- Avoid unnecessary table locks
- Use appropriate transaction isolation levels
- Monitor lock waits and deadlocks regularly
- Optimize queries to reduce the time locks are held
Reducing lock contention is a critical step in How to Fix Slow MySQL Queries because lock waits can delay otherwise efficient queries. By managing transactions carefully and minimizing unnecessary locking, you can improve concurrency, reduce response times, and maintain consistent database performance as your application scales.
16. Monitor Performance Continuously
Fixing slow queries once is not enough. New features, traffic growth, plugins, imports, and schema changes can create new slow queries.
MySQL Performance Schema helps monitor server execution at a low level and can be used for query profiling.
Track:
- Slowest queries
- Most frequent queries
- Query execution time
- Rows examined
- Lock waits
- CPU usage
- Memory usage
- Disk I/O
- Index usage
Use monitoring tools such as MySQL Performance Schema, Percona Monitoring and Management, Grafana, Datadog, New Relic, or cloud database dashboards.
Continuous monitoring ensures that improvements made while learning How to Fix Slow MySQL Queries remain effective as traffic, workloads, and data volumes grow.
Practical Example: Fixing a Slow MySQL Query
Slow query:
SELECT *
FROM orders
WHERE customer_id = 25
ORDER BY created_at DESC
LIMIT 10;
Problem:
- Uses
SELECT * - No proper index
- Sorts too many rows
Optimized version:
CREATE INDEX idx_orders_customer_created
ON orders(customer_id, created_at);
Better query:
SELECT id, total, status, created_at
FROM orders
WHERE customer_id = 25
ORDER BY created_at DESC
LIMIT 10;
Result:
- Fewer columns returned
- Better index usage
- Faster sorting
- Lower server load
This example demonstrates How to Fix Slow MySQL Queries by combining proper indexing with efficient column selection. Small query changes like these can significantly improve database performance.
Common MySQL Query Optimization Mistakes

Even when trying to improve database performance, many developers make mistakes that can actually make queries slower. If you’re learning How to Fix Slow MySQL Queries, avoid these common pitfalls:
- Adding random indexes without checking EXPLAIN
- Using too many indexes
- Ignoring slow query logs
- Using
SELECT *everywhere - Using large OFFSET pagination
- Running reports on production tables without caching
- Forgetting to index JOIN columns
- Using functions on indexed columns
- Not testing changes on real data
- Ignoring database locks
Avoiding these common mistakes is a critical part of learning How to Fix Slow MySQL Queries because even a well-configured server cannot compensate for inefficient SQL practices.
Best Tools to Find Slow MySQL Queries
Using the right tools can make a huge difference when learning How to Fix Slow MySQL Queries. These tools help identify bottlenecks, analyze execution plans, monitor database activity, and uncover performance issues before they impact users.
| Tool | Use |
|---|---|
| Slow Query Log | Find slow SQL statements |
| EXPLAIN | See estimated query plan |
| EXPLAIN ANALYZE | See real execution details |
| Performance Schema | Monitor low-level execution |
| mysqldumpslow | Summarize slow query logs |
| pt-query-digest | Analyze query patterns |
| PMM | Database monitoring |
| Grafana | Performance dashboards |

