MySQL Slow Query Log: How to Find and Fix Slow Queries

MySQL Slow Query Log: How to Find and Fix Slow Queries

A slow site does not always mean a slow server. On many small VPS setups, one or two database queries do most of the damage, while the rest of the stack waits for them. The MySQL slow query log gives you a record of those queries, with timing, so you can stop guessing and start with the worst one first.

This guide shows how to turn the log on, rank the entries, and fix the queries at the top. It works for MySQL and, with the same settings, for MariaDB on a self-managed VPS. Before you blame the database, check whether the database or something else is the bottleneck.

What the MySQL Slow Query Log Records

The log records queries that take longer than a threshold you set. Each entry includes the query text, how long it ran, how many rows it examined, how many rows it sent back, and when it ran. That combination matters. A query that runs for two seconds once a day is less urgent than one that runs for half a second a hundred times a minute.

The log does not explain why a query is slow. It points you at candidates. You still need to read the query plan before you change anything. It also misses queries that are fast on their own but called far too often, unless you lower the threshold or log queries without an index.

How to Enable the MySQL Slow Query Log

You can turn the log on without a restart, which is handy for a short test. Connect to MySQL as a user with administrative rights and run:

SET GLOBAL slow_query_log = 'ON';
SET GLOBAL slow_query_log_file = '/var/log/mysql/mysql-slow.log';
SET GLOBAL long_query_time = 1;

Here, long_query_time = 1 means any query over one second gets logged. Start with one second on a busy site and two seconds on a quiet one. A threshold of zero would log everything and fill the disk fast, so do not use it on a live server. Check that the change took effect with SHOW VARIABLES LIKE 'slow_query%'; and SHOW VARIABLES LIKE 'long_query_time';.

Settings made with SET GLOBAL disappear after a MySQL restart. To keep them, add the same values to your MySQL configuration file, usually /etc/mysql/my.cnf or a file under /etc/mysql/mysql.conf.d/, in the [mysqld] section:

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

Then restart MySQL and confirm the log file exists and grows. Keep these settings together with your other MySQL tuning settings so a later edit does not wipe them out. One optional setting, log_queries_not_using_indexes = 1, also logs queries that scan a table without an index. Use it for a short test, not as a permanent default, because it can flood the log on a WordPress site.

Reading the Log: What Each Entry Tells You

A raw entry looks dense at first, but only a few fields drive your next step. Query time is how long MySQL spent running the query. Lock time is how long it waited for a lock. Rows examined tells you how much work it did, and rows sent tells you how much of that work was useful.

A query that examines 200,000 rows to send back 10 rows is a strong candidate for an index. A query with high lock time points at a different problem, such as long transactions or a table that many writers touch at once. A query that runs slowly at the same time every day may match a cron job or a backup. Do not read a long log line by line. The same query can appear hundreds of times, so group and rank the repeats with the tools below.

Find Slow Queries with mysqldumpslow

mysqldumpslow ships with MySQL, so you can use it without installing anything extra. It groups similar queries together and sorts them by total time, count, or average time. To find slow queries, start with the ten queries that consumed the most total time:

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

The -s t flag sorts by total time, and -t 10 limits the output to ten groups. To sort by how often a query runs instead, use -s c. A query that appears thousands of times deserves attention even when each run looks short on its own.

Going Deeper with pt-query-digest

When mysqldumpslow is not enough, pt-query-digest from Percona Toolkit gives a fuller report. It shows total time per query pattern, time distribution, and the tables each pattern touches. Install the toolkit from your distribution packages, then point the tool at the log file:

pt-query-digest --limit 10 /var/log/mysql/mysql-slow.log

Start at the top and work down. The first few patterns often account for most of the logged time, so fixing one of them can change the whole picture. Save the report before you change anything, so you have a baseline to compare against after the fix.

Read EXPLAIN Before You Change Anything

Once you have a candidate query, run EXPLAIN on it. The output shows how MySQL plans to run the query: which tables it reads, in what order, which index it uses, and roughly how many rows it expects to examine. Look for type: ALL, which means a full table scan, and for Extra values such as Using filesort or Using temporary.

EXPLAIN SELECT id, title FROM posts
WHERE author_id = 42 AND status = 'publish'
ORDER BY created_at DESC LIMIT 10;

MySQL 8.0.18 and later also supports EXPLAIN ANALYZE, which runs the query and shows the actual time spent at each step. Use it outside peak hours on large tables. A large gap between planned and actual row counts often means stale table statistics, which you can refresh with ANALYZE TABLE. Do not add an index just because a query is slow. Check the WHERE, JOIN, and ORDER BY clauses first. An index helps when it matches the columns the query filters or sorts by, in the order the query uses them.

Common Fixes for Slow Queries

Most slow queries on a small VPS fall into a few repeatable patterns. Work through them in order, and re-check the log after each change.

First, add a missing index. A typical case is a query that filters by two columns, such as user_id and status, with no index on either one. MySQL then reads the whole table for every run. A composite index on (user_id, status) lets it jump straight to the matching rows, so the same query examines far fewer rows and drops down the ranking.

Second, shrink what the query asks for. SELECT * pulls every column, including large text fields you may not need. List only the columns the page uses. If the code only shows ten rows, add a LIMIT instead of fetching thousands and trimming them in code.

Third, fix the shape of the filter. A LIKE '%word%' pattern with a leading wildcard cannot use a normal index. A function wrapped around an indexed column, such as DATE(created_at) = '2026-11-01', has the same effect. Rewrite the condition as a range when you can, for example created_at >= '2026-11-01' AND created_at < '2026-11-02', so the index stays usable.

WordPress sites have their own version of this problem. Bloated tables and plugins that run heavy queries on every page load show up in the log as repeat patterns. If you run WordPress, clean up bloated WordPress tables after you find the offending queries. Keep each fix small and test it. Add one index, re-run the query with EXPLAIN, and watch the log for a day. Every extra index slows down writes and takes disk space. That trade-off is the heart of MySQL query optimization: an index that speeds up reads has a cost on every insert and update.

How Long to Keep Logging On, and When to Turn It Off

Leave the log on for at least a full day, so it covers peak traffic, quiet hours, and any scheduled jobs. A few minutes of logging during a quiet period will miss the queries that only appear when the site is busy. Check the file size daily while you tune, and rotate it with logrotate.

Turn the log off, or raise long_query_time, once you have fixed the top patterns and the log goes quiet. Logging costs some overhead, and a log that nobody reads is just disk use. Keep the settings in your configuration file so you can switch logging back on quickly. The same approach works for MariaDB, and the MariaDB tuning guide for low-memory VPS setups covers the settings that sit next to the log in the same file. When the same pattern returns after a fix, re-read the query instead of adding a bigger index.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.