Plenty of servers have the MySQL slow query log switched on, and nobody has opened it in months. The log keeps recording the same expensive queries every day. The first anyone hears about it is a batch of tickets saying checkout times out or the admin panel hangs. When someone finally looks, it turns out the evidence was on disk the whole time.
This article walks through that pattern as a post-mortem, then shows how a weekly review with mysqldumpslow catches it earlier. It describes a common pattern pieced together from many incidents, not one specific incident.
Initial impact: timeouts with no obvious cause
The first symptoms rarely point at the database. Users see slow pages, intermittent 504 or 502 errors from the web server, or forms that spin and then fail. Sometimes the application logs show Too many connections. That error means MySQL hit its max_connections limit because earlier queries were still running and holding their connections open.
The pattern is usually gradual. A query that was fine when a table had a few thousand rows becomes expensive when the table has a few million. Nothing in the code changed. The data grew, and a query without a suitable index now reads the whole table every time it runs. Each run takes a little longer, more requests pile up behind it, and at some point peak traffic pushes it over the edge.
From the support desk, the customer report is almost always some version of "the site is slow." The first job is to find out whether the database is the bottleneck at all, or whether PHP workers, the disk, or the network are the real limit.
How the investigation usually goes
The early steps are familiar. Someone checks the web server and PHP error logs, then opens top and sees mysqld using a lot of CPU. Running SHOW FULL PROCESSLIST in MySQL shows the same query, with slightly different values, appearing many times at once. That repetition is the first real clue.
The next question is whether the slow query log was even capturing anything. The slow query log is a file where MySQL or MariaDB records every query that takes longer than the long_query_time threshold, measured in seconds. Three variables tell you whether it is on, where it writes, and what counts as slow:
SHOW VARIABLES LIKE 'slow_query_log';
SHOW VARIABLES LIKE 'slow_query_log_file';
SHOW VARIABLES LIKE 'long_query_time';
-- Optional capture test: sleep longer than long_query_time, then check the log file
SELECT SLEEP(11);
If slow_query_log is OFF, logging is disabled. If it is ON, the file path tells you where to look. The SLEEP() test comes from a commonly shared GitHub gist on enabling the slow query log. It forces a query that should land in the log, which proves the log is actually being written. Adjust the sleep value so it is higher than your own long_query_time.
If the log turns out to be empty even though the site is slow, the cause is usually the threshold or file permissions, which is a separate problem. That case is covered in Site Is Slow but the MySQL Slow Query Log Is Empty, Lower long_query_time?.
The discovery: the log already had the answer
In this pattern, the log is not empty. It is large, sometimes hundreds of megabytes, because it has been recording the same offenders for weeks. Nobody was reading it, mostly because reading it raw is unpleasant. Every entry is a separate block with timing, rows examined, and the full query text, so a busy server produces thousands of nearly identical blocks.
That is the job mysqldumpslow does. It ships with MySQL (on newer MariaDB it may be named mariadb-dumpslow). It reads the slow log and groups queries that differ only in their values. Numbers are replaced with N and strings with 'S', so a thousand lookups for different order IDs collapse into one line with a count.
# Top 10 query patterns by total time spent
mysqldumpslow -s t -t 10 /path/from/slow_query_log_file
# Top 10 by how often they ran
mysqldumpslow -s c -t 10 /path/from/slow_query_log_file
# Weekly report via crontab (Monday 07:00); note that % must be escaped in crontab
0 7 * * 1 mysqldumpslow -s t -t 20 /path/from/slow_query_log_file > /root/slow-report-$(date +\%F).txt
The sort order matters. Sorting by total time (-s t) shows where the server spent most of its effort. Sorting by count (-s c) shows what runs constantly. The query that causes outages is usually not the rare 30-second report. It is more often a query that takes one or two seconds and runs thousands of times a day, because every run holds a connection and competes for CPU and I/O.
Illustrative output format (values are invented and rounded):
Count: 1200 Time=2.00s (2400s) Lock=0.00s (0s) Rows=20.0 (24000), app_user[app_user]@localhost
SELECT * FROM orders WHERE status = 'S' ORDER BY created_at DESC LIMIT N
Read that as: this pattern ran 1,200 times, averaged two seconds, and consumed 2,400 seconds of query time in total. A pattern like that is the critical finding in most of these post-mortems. The raw log entries also include Rows_examined next to Rows_sent. When a query examines hundreds of thousands of rows to return twenty, an index is almost certainly missing.
Temporary mitigation: confirm, then add the index carefully
Before changing anything, confirm the diagnosis. Run EXPLAIN in front of a real instance of the query, with actual values in place of N and 'S'. Warning signs are type: ALL, which means a full table scan, key: NULL, and a rows estimate close to the size of the table.
For the example above, a composite index that matches both the filter and the sort usually helps: ALTER TABLE orders ADD INDEX idx_status_created (status, created_at);. The column order follows the query. status comes first because of the equality filter, and created_at second because of the ORDER BY. Run EXPLAIN again afterwards and check that the new index appears in the key column.
Be careful with this step on a live server. Adding an index to a large table can take a long time and use a lot of I/O. Depending on the MySQL or MariaDB version and the table definition, it may block writes while it runs. Take a backup first, test on a copy if you can, and run it during low traffic. If the table belongs to an application such as a CMS plugin, check whether the vendor already provides an index or an update, because a later application update may clash with schema changes it does not know about.
Other quick fixes are tempting but treat the symptom. Raising max_connections lets more slow queries pile up at once, which often makes the server slower. Killing long-running queries with KILL can free connections in an emergency, but the application will send the same query again a moment later.
The lasting fix: a weekly review that someone owns
The real failure in this pattern is that nobody owned the log. Turning it on felt like enough. A lasting fix is a small routine with a named owner.
Once a week, generate the mysqldumpslow report sorted by total time and by count, and compare it with last week's report. New entries near the top deserve attention, especially after a plugin update, a new feature, or a data import. Patterns that stay at the top week after week are candidates for an index or a query rewrite. Patterns that drop off after a fix confirm that the fix worked. The review usually takes a few minutes once the reports are generated automatically.
A few supporting habits keep the routine working:
- Rotate the log. An unrotated slow log grows without limit and competes for disk space with your data, a problem covered in Why MySQL Crashes When Binary Logs Silently Fill Your Disk. With logrotate, have the rotation run
FLUSH SLOW LOGSafterwards so MySQL reopens the file instead of writing into the rotated copy. - Make the settings persistent.
SET GLOBAL slow_query_log = 'ON'is lost on restart unless the setting is also in the config file. MySQL 8.0 and later can useSET PERSISTinstead. - Use
log_queries_not_using_indexeswith care. It can reveal unindexed queries that are still fast today, but on a busy server it gets noisy quickly. Turn it on briefly, review the output, and turn it off again. - Switch tools when you outgrow this one. For more detailed breakdowns, tools such as
pt-query-digestfrom Percona Toolkit read the same log and report percentiles and rows examined per pattern.
The practical takeaway: confirm today that the slow query log is on and actually capturing queries, then schedule one weekly report sorted by total time. When a pattern keeps appearing near the top, run EXPLAIN on it before the next traffic peak. This usually turns a future outage into a planned index change made at a quiet hour.