Skip to content

MySQL Slow Query Log: Find and Fix Slow Queries

MySQL slow query log is one of the most useful tools for identifying database queries that delay website loading, increase server resource usage, and reduce application performance. Instead of guessing why a website is slow, administrators can use this log to identify queries that take longer than a defined execution-time threshold.

A slow website does not always indicate a problem with CPU, RAM, or network connectivity. In many cases, inefficient SQL queries, missing indexes, large table scans, or poorly optimized database operations are responsible for the delay. The MySQL slow query log helps administrators investigate these issues using actual database activity.

In this guide, you will learn how to enable the MySQL slow query log, configure appropriate thresholds, analyze recorded queries, use EXPLAIN to investigate execution plans, and identify practical opportunities to improve database performance on a Linux VPS or dedicated server.

What Is the MySQL Slow Query Log?

The MySQL slow query log records SQL statements that take longer than a configured execution-time threshold. Depending on the server configuration, it can also record queries that do not use indexes for row lookups.

Database administrators use this information to find inefficient queries without manually inspecting every SQL statement executed by an application.

For example, a WordPress website might experience slow page generation because a plugin repeatedly executes an expensive query. An e-commerce application might take several seconds to display products because a query scans a large table without an appropriate index.

The slow query log provides evidence that helps narrow down these problems.

Why slow queries matter

Slow database queries can affect a website in several ways:

  • Increase page generation time and API response latency.
  • Keep database connections occupied for longer periods.
  • Consume excessive CPU or disk I/O resources.
  • Reduce the number of requests a server can process efficiently.
  • Contribute to application timeouts during periods of high traffic.
  • Cause database contention when expensive operations overlap.

A query taking 500 milliseconds might not be problematic when executed occasionally. However, if the same query runs hundreds of times per minute, its cumulative cost can become significant.

The goal is not to eliminate every query that exceeds a fixed duration. It is to identify queries whose execution cost meaningfully affects the application.

How the MySQL Slow Query Log Works

MySQL checks eligible query execution times against the configured long_query_time threshold. When a query meets the logging conditions, MySQL can write information about it to the configured slow query log.

The log commonly contains details such as:

  • Query execution time.
  • Lock time.
  • Rows sent to the client.
  • Rows examined during query execution.
  • The SQL statement that was executed.
  • A timestamp and additional session or server metadata, depending on the version and configuration.

These fields help administrators distinguish between queries that process too many rows and queries that spend time waiting for locks or other resources.

For example, a query that examines 500,000 rows to return five results may indicate an inefficient access path. A query with substantial lock time may instead point toward contention or a transaction-management problem.

The slow query log does not automatically explain why a query is slow. It identifies candidates for further investigation.

Step 1: Check Your MySQL Server Configuration

Before enabling logging, verify which database server and version you are using. MySQL and MariaDB share many configuration concepts, but supported variables and administrative commands can differ by version.

Connect to the database using an account with the required privileges:

mysql -u root -p

On some managed or control-panel servers, the administrative account or connection method may be different.

Check the server version:

SELECT VERSION();

Inspect the current slow query log settings:

SHOW VARIABLES LIKE 'slow_query_log';
SHOW VARIABLES LIKE 'slow_query_log_file';
SHOW VARIABLES LIKE 'long_query_time';
SHOW VARIABLES LIKE 'log_output';
SHOW VARIABLES LIKE 'log_queries_not_using_indexes';

These commands reveal whether logging is enabled, where the log is written, the execution-time threshold, and whether the destination is a file or a table.

Pay attention to log_output. If it is set to FILE, the server writes to a log file. If it is set to TABLE, slow query records are stored in the mysql.slow_log table. A configuration can also use FILE,TABLE.

If logging is already enabled, inspect the existing configuration before making changes.

Step 2: Enable the MySQL Slow Query Log

For a temporary diagnostic session, enable the slow query log dynamically:

SET GLOBAL slow_query_log = 'ON';

This requires the appropriate administrative privileges. The exact privilege requirements depend on the MySQL version and account configuration.

Next, set a reasonable execution-time threshold:

SET GLOBAL long_query_time = 1;

This sets the threshold to one second for new sessions that inherit the global value. Existing database sessions may retain their session-level setting, so verify the effective value where necessary.

A one-second threshold is a reasonable starting point for some investigations, but it is not universal. A latency-sensitive application may require a lower threshold, while a busy production database may need a higher threshold initially to control log volume.

Check the updated values:

SHOW GLOBAL VARIABLES LIKE 'slow_query_log';
SHOW GLOBAL VARIABLES LIKE 'long_query_time';

Important: Dynamic changes may not persist after a database service restart. For long-term configuration, update the server configuration file using the method supported by your distribution or hosting environment.

Step 3: Configure the Slow Query Log Permanently

MySQL configuration files are commonly located under /etc/mysql/ or /etc/, although the exact path depends on the operating system and installation method.

On many Linux installations, a server configuration file may be named mysqld.cnf or my.cnf.

Locate the applicable configuration file before editing it. For example:

sudo find /etc/mysql /etc -maxdepth 3 \
  -type f \( -name 'my.cnf' -o -name 'mysqld.cnf' \) \
  2>/dev/null

Do not edit every matching file. Identify which files are actually included by the running server configuration.

Inside the appropriate server section, commonly [mysqld], add or adjust settings similar to these:

[mysqld]
slow_query_log = ON
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 1
log_output = FILE

The log path is an example. Confirm that the directory exists and that the MySQL service account can write to it. Some distributions and control panels use a different log directory or manage database settings through their own configuration tools.

Before restarting MySQL, back up the configuration file and validate the proposed changes against your server version and operational requirements.

Restarting a database service can interrupt active connections. Schedule the restart during an appropriate maintenance window if your environment requires one. If your version supports the necessary dynamic variables, some changes may be applied without restarting the service.

After applying the configuration, verify the settings:

SHOW GLOBAL VARIABLES LIKE 'slow_query_log';
SHOW GLOBAL VARIABLES LIKE 'slow_query_log_file';
SHOW GLOBAL VARIABLES LIKE 'long_query_time';
SHOW GLOBAL VARIABLES LIKE 'log_output';

If the log remains empty, generate a controlled test query that exceeds the threshold, then check whether the record appears.

Step 4: Find and Read the Slow Query Log

When log_output is set to FILE, inspect the configured log file from the Linux shell.

For example:

sudo tail -n 100 /var/log/mysql/mysql-slow.log

To follow new entries as they are written:

sudo tail -f /var/log/mysql/mysql-slow.log

Use Ctrl+C to stop following the log.

If you need to search for query records or related metadata, grep can help:

sudo grep -n -i 'SELECT' /var/log/mysql/mysql-slow.log

This searches for lines containing SELECT; it is only a basic text search, not a complete SQL parser. Multiline queries and comments may make simple searches less useful.

A slow query entry may look similar to this:

# Query_time: 2.450000  Lock_time: 0.000100
# Rows_sent: 10  Rows_examined: 450000
SELECT id, title
FROM articles
WHERE category_id = 12;

This is an illustrative example, not a result from a real server.

The query took approximately 2.45 seconds, returned 10 rows, and examined 450,000 rows. That difference is a strong reason to investigate the query plan and available indexes.

What the important fields mean

Query_time: The time spent executing the query, as reported in the log.

Lock_time: The time associated with acquiring locks, as reported by the server. Interpretation depends on the query type and database version; it should not be treated as a complete measurement of every kind of contention.

Rows_sent: The number of rows returned to the client.

Rows_examined: The number of rows examined by the server while processing the query. A large value relative to the number of returned rows can indicate an inefficient access path, although some queries legitimately examine many rows.

These values are clues rather than definitive diagnoses. Review them alongside the SQL statement, query plan, table structure, indexes, and application behavior.

Step 5: Use EXPLAIN to Investigate Slow Queries

After identifying a slow SQL statement, inspect its execution plan with EXPLAIN.

For example:

EXPLAIN
SELECT id, title
FROM articles
WHERE category_id = 12;

The output describes how MySQL plans to retrieve the requested data. It can show the selected table access method, candidate indexes, the chosen key, estimated rows, and other information.

For supported MySQL versions, EXPLAIN ANALYZE can execute a query and report actual execution details alongside the plan:

EXPLAIN ANALYZE
SELECT id, title
FROM articles
WHERE category_id = 12;

Use EXPLAIN ANALYZE carefully. Unlike ordinary EXPLAIN, it executes the statement being analyzed. It is intended for supported query types and versions, and the query can consume significant CPU, memory, or disk I/O. Do not casually run expensive queries against a busy production database.

What to look for in EXPLAIN output

Full table scans: A plan that reads an entire large table may indicate a missing or unsuitable index. However, a full scan can be the best plan for small tables or queries that need a large proportion of the rows.

Possible keys and selected keys: Check whether useful indexes are available and whether the optimizer chooses one. An index existing on a table does not guarantee that it is suitable for a particular query.

Estimated rows: A high estimated row count can indicate that the query needs to inspect a large amount of data. Compare estimates with actual execution details when available.

Filtering: If the server reads many rows but retains very few, investigate the filtering conditions and access path.

Temporary tables and sorting: Operations involving temporary tables or filesorts may be expensive for some workloads. Their presence alone does not prove a performance problem; examine the actual workload and query plan.

A query plan should be interpreted as a whole. Avoid adding indexes or rewriting SQL based on a single field without understanding the table structure and data distribution.

Step 6: Identify Common Causes of Slow Queries

Once the execution plan is available, investigate the most likely causes.

1. Missing or unsuitable indexes

Consider this query:

SELECT id, title
FROM articles
WHERE category_id = 12;

If category_id is frequently used to filter a large table, an index on that column may help:

CREATE INDEX idx_articles_category_id
ON articles (category_id);

This is an example, not a universal recommendation. Confirm the table definition and existing indexes before adding anything.

Indexes require storage and add overhead to inserts, updates, and deletes. Low-selectivity columns or workloads that retrieve most of a table may not benefit as expected.

2. Selecting unnecessary columns

Avoid retrieving every column when the application only needs a few fields.

Instead of:

SELECT *
FROM articles
WHERE category_id = 12;

Use:

SELECT id, title
FROM articles
WHERE category_id = 12;

Selecting fewer columns can reduce data transfer and memory consumption. It may also allow a suitable covering index to satisfy a query, depending on the table and index design.

3. Inefficient filtering and sorting

Review queries that combine multiple filters, sorting, and pagination.

For example:

SELECT id, title, created_at
FROM articles
WHERE category_id = 12
ORDER BY created_at DESC
LIMIT 20;

Depending on the workload and existing indexes, a composite index such as (category_id, created_at) may help. The ideal index depends on sort direction support, column definitions, query patterns, and the database version.

Test index changes using representative queries and realistic data.

4. Expensive joins

Queries joining multiple large tables can become expensive when join conditions are not indexed appropriately or when the query processes more rows than necessary.

Inspect the plan for each table involved. Verify join columns, filter conditions, and whether the optimizer can use suitable indexes. Avoid assuming that every join is slow; well-designed joins are normal and often efficient.

5. Large offsets in pagination

A query using LIMIT 20 OFFSET 100000 may require the database to scan or skip many rows before returning the requested page.

For large datasets, keyset pagination can be more efficient when the application has a stable ordering key. For example:

SELECT id, title
FROM articles
WHERE id > 50000
ORDER BY id
LIMIT 20;

This example assumes that the application is paginating by an appropriate increasing id. Real applications must preserve the intended ordering and account for gaps, concurrent changes, and filters.

6. Lock contention and long transactions

Not every slow query is caused by poor SQL or missing indexes. Transactions that hold locks for too long can delay other operations.

Investigate transaction duration, blocked sessions, and lock waits using the diagnostic facilities available in your MySQL version. Avoid terminating sessions blindly, because doing so can roll back work or disrupt application operations.

Step 7: Review Queries Without Indexes Carefully

MySQL can optionally log queries that do not use indexes for row lookups. This setting may help during an investigation:

SET GLOBAL log_queries_not_using_indexes = ON;

However, enabling this option can significantly increase log volume, particularly on busy servers or applications that legitimately scan small tables.

A query that does not use an index is not automatically inefficient. For example, a full scan of a small lookup table can be faster than an index lookup. The objective is to identify expensive queries, not to force index usage everywhere.

For targeted troubleshooting, consider combining this setting with an appropriate logging threshold or other version-supported controls. Verify the available variables on your database server before applying them.

Disable additional logging when the investigation is complete if it is no longer needed:

SET GLOBAL log_queries_not_using_indexes = OFF;

Step 8: Summarize Slow Queries with mysqldumpslow

A slow query log can become difficult to analyze manually when it contains thousands of entries. MySQL provides mysqldumpslow to summarize and sort queries from the log.

For example:

sudo mysqldumpslow -s t -t 10 \
  /var/log/mysql/mysql-slow.log

This requests the top 10 query patterns sorted by average query time. The -s t sort option uses average query time; use the documentation for your installed version to confirm the available sort options.

To rank query patterns by total query time, use:

sudo mysqldumpslow -s at -t 10 \
  /var/log/mysql/mysql-slow.log

The total time can help identify query patterns that consume a large amount of time collectively, even if individual executions are not the slowest.

Other supported sort options may include counts, lock time, rows sent, and rows examined. Check the local manual page:

man mysqldumpslow

Query normalization and aggregation can hide differences between parameter values, so investigate representative statements before making changes.

Step 9: Monitor the Results After Optimization

After modifying a query or adding an index, measure its impact instead of assuming that the change worked.

Use a repeatable process:

  1. Record the original query execution time and relevant plan details.
  2. Test the change with representative data and application parameters.
  3. Compare execution plans and actual timings where supported.
  4. Monitor CPU, disk I/O, database connections, and application response time.
  5. Verify that inserts and updates have not become unnecessarily expensive.
  6. Observe the application under realistic traffic conditions.

A query that performs well against a small development database may behave differently when the production table contains millions of rows. Data distribution, cache state, concurrent workload, and hardware can all influence results.

Do not rely on a single execution time as the only measure of success. Consider repeatability and the broader impact on application performance.

Step 10: Manage Log Growth and Production Overhead

Slow query logging adds diagnostic overhead and consumes disk space. The impact depends on query volume, threshold settings, logging destinations, and server workload.

On a production VPS, start with a targeted threshold and monitor the resulting log size.

Check the configured file:

sudo ls -lh /var/log/mysql/mysql-slow.log

Confirm that log rotation is configured appropriately for your installation. Do not delete or truncate a log file blindly while MySQL is writing to it. Use the rotation or log-reopen procedure supported by your server and operating system.

When an investigation is complete, disable logging if continuous collection is unnecessary:

SET GLOBAL slow_query_log = 'OFF';

If you need ongoing performance visibility, consider a monitoring solution that tracks query patterns, latency, and resource consumption over time. Be careful when sharing slow query logs because statements can contain personal data, email addresses, identifiers, or other sensitive values.

Common MySQL Slow Query Log Problems

The slow query log is enabled, but the file is empty

Check the configured threshold, log destination, file path, and effective settings for the relevant sessions. The workload may not contain queries that meet the threshold. You can run a controlled test query on a non-production environment to verify that logging works.

The log file cannot be opened

Confirm the configured path, directory permissions, available disk space, and service account access. Security controls such as SELinux or AppArmor may also affect file access.

Queries remain slow after adding an index

Review the new execution plan, data distribution, and actual query behavior. The index may not match the filter or sort pattern, the optimizer may reasonably prefer a different access path, or the main bottleneck may be locking, I/O, or application behavior.

The log contains too many entries

Increase the threshold, narrow the investigation, or temporarily disable additional logging of queries that do not use indexes. Be sure to preserve enough diagnostic information to investigate the problem.

The query plan looks good, but the website is still slow

The database may not be the main bottleneck. Investigate application code, external API calls, network latency, PHP-FPM worker availability, caching, and other server components. Use correlated timestamps to connect database activity with slow application requests.

MySQL Slow Query Log Best Practices

Follow these practices when investigating database performance:

  • Start with the existing configuration and collect evidence before making changes.
  • Choose a threshold appropriate for the application and workload.
  • Review both execution time and rows examined.
  • Use EXPLAIN to understand the query plan.
  • Run EXPLAIN ANALYZE only when supported and safe for the target query.
  • Check existing indexes before creating new ones.
  • Test changes with representative data.
  • Monitor log size and server resource usage.
  • Protect logs because SQL statements may contain sensitive information.
  • Document configuration changes and revert temporary diagnostic settings when appropriate.

Frequently Asked Questions

What is the default MySQL slow query log threshold?

The commonly documented default for long_query_time in MySQL is 10 seconds, but defaults and effective values can vary by version, configuration, and hosting environment. Check your actual server setting with SHOW VARIABLES LIKE 'long_query_time';.

Does enabling the MySQL slow query log affect performance?

It can add overhead, particularly when a large number of queries are logged. The impact depends on workload, threshold, and logging destination. Use targeted settings and monitor production performance.

How do I find the slowest MySQL queries?

Enable the slow query log, choose a suitable threshold, and analyze the output with tools such as mysqldumpslow. For deeper analysis, inspect individual queries with EXPLAIN and, where supported and safe, EXPLAIN ANALYZE.

Does adding an index always make a query faster?

No. Indexes can improve data retrieval, but they consume storage and add write overhead. The best index depends on query conditions, data distribution, and the workload.

Can I enable slow query logging without restarting MySQL?

In many MySQL versions, the slow query log and certain related variables can be changed dynamically using SQL statements, provided the account has the required privileges. Permanent configuration may still require updating a configuration file.

Should I keep the slow query log enabled permanently?

That depends on your performance-monitoring needs and resource budget. Some environments keep it enabled with a suitable threshold, while others enable it temporarily during troubleshooting. Monitor log growth and diagnostic overhead before deciding.

Conclusion

The MySQL slow query log helps administrators move from guessing about database performance to investigating real SQL execution behavior. By enabling logging, reviewing execution times and rows examined, inspecting query plans with EXPLAIN, and measuring changes, you can identify database bottlenecks and make informed optimization decisions.

For reliable results, treat the log as the starting point of a diagnostic process rather than an automatic list of queries that must be changed. Validate each optimization against actual workload behavior, protect production resources, and monitor the results after every significant change.

For more Linux VPS administration and performance troubleshooting guides, explore the ServerNext blog.

Official references: