← All posts
Operations· 7 min read

MySQL slow query log: a practical guide for small teams

Enable the MySQL slow query log, read it with mysqldumpslow, and fix the queries killing your app. Step-by-step for teams without a DBA.

By , Founder of Opservo (LinkedIn) · Updated

Your app slows down at peak time, users complain, and you have no idea which database query is the culprit. This is the most common situation for small engineering teams running MySQL without a dedicated DBA. The slow query log is MySQL's built-in way to catch those queries. It records every query that takes longer than a threshold you set. This guide shows you how to turn it on, read it, act on it, and know when to alert.

What the slow query log actually records

Every query that exceeds `long_query_time` (in seconds) is written to the log. Each entry shows the execution time, the rows examined, the rows sent, the timestamp, the user and host, and the full query text. That is enough to tell you which query is slow, how often it runs, and whether it is scanning too many rows.

Two settings control what gets captured. `long_query_time` is the threshold in seconds. It accepts decimals, so `0.5` means 500 ms. `log_queries_not_using_indexes` is a flag that logs any query that skips an index, even if it finishes quickly. Both are worth enabling in production once you understand the volume they produce.

Rule of thumb: start with long_query_time = 1 and tighten it to 0.5 once you have cleared the obvious offenders. Logging everything under 100 ms on a busy server produces a large file fast.

How to enable the slow query log without restarting MySQL

You can enable it at runtime with `SET GLOBAL`. The change takes effect immediately but does not survive a restart unless you also add it to `my.cnf`. Do both.

-- 1. Enable at runtime (no restart needed)
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
SET GLOBAL slow_query_log_file = '/var/log/mysql/slow.log';
SET GLOBAL log_queries_not_using_indexes = 'ON';

-- 2. Confirm the settings took effect
SHOW VARIABLES LIKE 'slow_query_log%';
SHOW VARIABLES LIKE 'long_query_time';

-- Expected output (values match what you just set):
-- slow_query_log       | ON
-- slow_query_log_file  | /var/log/mysql/slow.log
-- long_query_time      | 1.000000

-- 3. Persist across restarts: add to /etc/mysql/mysql.conf.d/mysqld.cnf
-- (or /etc/my.cnf depending on your distro)
--
-- [mysqld]
-- slow_query_log       = 1
-- slow_query_log_file  = /var/log/mysql/slow.log
-- long_query_time      = 1
-- log_queries_not_using_indexes = 1

# On the shell, check the file is growing:
sudo tail -f /var/log/mysql/slow.log

If `/var/log/mysql/slow.log` does not appear after a minute or two, check that the MySQL user has write permission to that directory. The quickest test is `sudo ls -la /var/log/mysql/`. If the directory is owned by root rather than mysql, run `sudo chown mysql:mysql /var/log/mysql/`.

Reading the log with mysqldumpslow

`mysqldumpslow` ships with MySQL. It groups identical queries (replacing literal values with `N` or `S`), counts how many times each ran, and totals the time. That makes it easy to find the worst offenders rather than reading raw log lines.

The two most useful invocations are shown below. The first shows the top ten queries by total time spent. The second shows the top ten by how often they appear. Run both: a query that runs ten thousand times a day at 50 ms each does far more damage than one that runs once and takes three seconds.

# Top 10 queries by total time (worst overall impact)
sudo mysqldumpslow -s t -t 10 /var/log/mysql/slow.log

# Top 10 queries by count (most frequent slow queries)
sudo mysqldumpslow -s c -t 10 /var/log/mysql/slow.log

# Sample output line:
# Count: 847  Time=2.31s (1956s)  Lock=0.00s (0s)  Rows=1024.0 (866528), app[app]@localhost
# SELECT * FROM orders WHERE status = 'S' AND created_at > 'S'
#
# Read as: ran 847 times, 2.31s average, 1956s total CPU,
# examined 1024 rows on average to return results.

# For a richer view, install pt-query-digest from Percona Toolkit:
sudo apt-get install percona-toolkit   # Debian/Ubuntu
pt-query-digest /var/log/mysql/slow.log | head -100

`pt-query-digest` gives you a percentage breakdown of where total query time goes, the min/max/p95 latency per query pattern, and fingerprinted query text. It is the right tool once you have more than a few hundred unique slow queries. The output is long but the top section is a ranked table you can read in two minutes.

What to do with a slow query once you find it

The first check is always `EXPLAIN`. Paste the query from the log (with real values restored) and run `EXPLAIN SELECT ...` in a MySQL client. Look at the `type` column. `ALL` means a full table scan. `index` means it scanned the whole index. Both are bad if the table is large. `ref` or `eq_ref` means it used an index efficiently.

Look at `rows`. If MySQL estimates it needs to examine 500,000 rows to return 10, an index is missing or the query is filtering poorly. The `Extra` column tells you if MySQL is sorting in memory (`Using filesort`) or building a temporary table (`Using temporary`). Both appear on queries that are missing a composite index covering the ORDER BY or GROUP BY columns.

Common fixes, in order of how often they help:

  • Add an index on the WHERE and ORDER BY columns together. Use `CREATE INDEX idx_name ON table (col1, col2)` and re-run EXPLAIN to confirm the type changes from ALL to ref.
  • Replace `SELECT *` with the specific columns you need. Fetching fewer columns reduces I/O and can allow a covering index.
  • For queries that join large tables and filter on both sides, check that both sides have indexes on the join column.
  • If the query runs frequently and the data changes infrequently, consider a Redis cache in front of it. This is a last resort, not a first step.
  • Check whether the query is an N+1 pattern: a loop in application code that fires one query per row of a previous result. The fix is a single JOIN or an eager-load in your ORM.

If your app is a Laravel project, the Laravel production monitoring guide covers how to surface N+1 queries and queue-worker slowdowns alongside database issues.

What to alert on: concrete thresholds

Enabling the log is only useful if someone notices when things get worse. These are the signals worth alerting on, with thresholds that fit most small production databases.

  • Slow query rate above 10 per minute: check with `SHOW GLOBAL STATUS LIKE 'Slow_queries'` polled every 60 seconds and alert on the rate of change. A sudden spike usually means a missing index after a schema change or a new code path hitting a large table.
  • Any single query pattern with a p95 latency above 2 seconds: this will be felt by end users. Alert and investigate the same day.
  • Full table scans (`Select_scan` in SHOW STATUS) increasing faster than your row count grows: a new query pattern is bypassing indexes.
  • Slow query log file size above 500 MB: rotate it with `FLUSH SLOW LOGS` and confirm log rotation is configured in `/etc/logrotate.d/mysql-server`.
  • Long_query_time left at the default of 10 seconds: the default is too loose to catch most user-visible slowness. Alert if the setting has not been tightened below 2 seconds in production.

You can query `SHOW GLOBAL STATUS` from a cron script or a monitoring agent and push those metrics to whatever alerting system you use. The key counter is `Slow_queries`. It increments for every query that exceeded `long_query_time`, so dividing the delta by your polling interval gives you queries per second.

Database slowness rarely happens in isolation. High slow-query rates often coincide with CPU saturation or memory pressure on the same host. If you are seeing slow queries and want to understand what else is happening on that server at the same time, the server slow checklist walks through CPU, memory, disk I/O and network in about ten minutes.

Keeping the log file manageable in production

The slow query log can grow fast, especially with `log_queries_not_using_indexes = ON`. Two things keep it under control.

First, set up log rotation. On Debian and Ubuntu, `/etc/logrotate.d/mysql-server` usually handles this already. Check that it rotates daily and keeps no more than 7 days. After rotation, MySQL continues writing to the old file descriptor until you run `FLUSH SLOW LOGS` or send a `SIGHUP`.

Second, once you have fixed the obvious slow queries, turn off `log_queries_not_using_indexes`. It is useful for an audit but adds noise once your indexes are healthy. You can re-enable it briefly after any major schema migration to catch new gaps.

If you are on a busy server and even `long_query_time = 0.5` fills the log too fast, consider enabling the Performance Schema instead. `events_statements_summary_by_digest` gives you aggregated query statistics without writing a file, and you query it with SQL. The tradeoff is that it has no persistent history across a restart unless you export it.

How Opservo helps teams without a DBA

If your team does not have someone watching MySQL metrics daily, Opservo auto-discovers your MySQL instance and surfaces slow query rate, connection saturation and replication lag alongside everything else on the server. The Opservo Health Standard scores each server 0-100, names every lost point with the current value and the fix, and alerts when slow queries spike. You do not need to build the polling script or the alert rule yourself.

Put these checks on your own server with the free 2-server plan, and see MySQL slow-down signals explained in plain English — one command installs a read-only agent and your first findings arrive in five minutes: start free. Related: Why is my server slow.