Skip to content

MySQL slow query log — enable, parse, and act on it

Turn on the slow query log without restarting MySQL, parse it with pt-query-digest, and use the output to prioritize the queries that actually matter.

The slow query log is the cheapest, most accurate source of truth about which queries are hurting MySQL. Turn it on, let it run for a representative window, parse it with pt-query-digest, and the top-of-list rows almost always include the index you forgot or the JOIN you wrote without thinking. This article walks the enable, parse, and act loop — and the safeguards that prevent the log itself from becoming an outage.

How to verify

To see whether the slow query log is on right now, where it writes, and what it includes:

SHOW VARIABLES LIKE 'slow_query_log%';
SHOW VARIABLES LIKE 'long_query_time';
SHOW VARIABLES LIKE 'log_queries_not_using_indexes';
SHOW VARIABLES LIKE 'min_examined_row_limit';
# If logging to file, peek at it
sudo tail -50 $(mysql -e "SHOW VARIABLES LIKE 'slow_query_log_file'\G" | grep Value | awk '{print $2}')

Defaults are usually slow_query_log = OFF, long_query_time = 10. Ten seconds is too high for almost any modern workload; sub-second is what you want.

What’s happening

MySQL writes a slow query log entry every time a query exceeds long_query_time seconds, or (optionally) every time a query runs without using an index. Each entry includes the query, the execution time, the lock time, rows examined, rows sent, and (in 8.0) the optimizer trace if you ask for it.

The log can go to a file (default) or a table (mysql.slow_log). File output is what pt-query-digest and similar tools expect; table output is searchable with SQL but harder to roll up. Either way, the runtime overhead of the log itself is small as long as the threshold keeps it from logging every query.

Setting long_query_time = 0 logs every query — which is useful for a short profiling window but disastrous as a default because it generates massive log volume and adds measurable latency. For steady-state monitoring, 0.1 (100 ms) or 0.5 is sensible. For deep profiling, drop to 0 for a 5-15 minute window and turn it back up.

The procedure

  1. Turn it on at runtime without restarting.

    SET GLOBAL slow_query_log = 1;
    SET GLOBAL long_query_time = 0.5;
    SET GLOBAL log_queries_not_using_indexes = 1;
    SET GLOBAL min_examined_row_limit = 100;

    min_examined_row_limit = 100 suppresses log entries for trivial small-table scans that would otherwise dominate output.

  2. Make the settings persistent. Edit /etc/mysql/mysql.conf.d/mysqld.cnf:

    [mysqld]
    slow_query_log              = 1
    slow_query_log_file         = /var/log/mysql/mysql-slow.log
    long_query_time             = 0.5
    log_queries_not_using_indexes = 1
    min_examined_row_limit      = 100
    log_slow_admin_statements   = 1
    log_slow_replica_statements = 1
  3. Confirm log file ownership and rotation. The log file must be writable by the mysql user; logrotate must include it.

    sudo ls -la /var/log/mysql/mysql-slow.log
    # Should be 0640 mysql:adm
    
    sudo cat /etc/logrotate.d/mysql-server
    # Should include a stanza for /var/log/mysql/mysql-slow.log

    If logrotate is missing, add:

    /var/log/mysql/mysql-slow.log {
        daily
        rotate 14
        missingok
        compress
        delaycompress
        create 0640 mysql adm
        postrotate
            mysqladmin --defaults-file=/etc/mysql/debian.cnf flush-logs
        endscript
    }
  4. Collect a representative window. Let it run for at least 24 hours so you capture the daily cron jobs, the report runs, and the off-peak compaction queries. Then snapshot:

    sudo cp /var/log/mysql/mysql-slow.log /tmp/mysql-slow-$(date +%F).log
  5. Parse with pt-query-digest. From the Percona Toolkit (sudo apt install percona-toolkit).

    pt-query-digest /tmp/mysql-slow-$(date +%F).log > /tmp/slow-digest-$(date +%F).txt
    less /tmp/slow-digest-$(date +%F).txt

    The output ranks query fingerprints by total time consumed. Each entry shows count, total time, mean time, 95th percentile, rows examined per execution, and a representative query string. The top 5-10 entries usually account for 80%+ of slow time — those are your work list.

  6. Investigate each top query with EXPLAIN.

    EXPLAIN FORMAT=JSON SELECT ... FROM ... WHERE ...;

    Look for type: ALL (full table scan), Extra: Using filesort, Extra: Using temporary. Each is a candidate for an index or a query rewrite. For composite indexes, the leftmost-prefix rule applies — write the columns in order of selectivity.

  7. Add the index in a low-traffic window. Use ALGORITHM=INPLACE, LOCK=NONE so the DDL does not block writes:

    ALTER TABLE orders ADD INDEX idx_customer_created (customer_id, created_at),
      ALGORITHM=INPLACE, LOCK=NONE;

    For very large tables, use pt-online-schema-change or gh-ost instead — they build a shadow table without blocking writes for the full duration.

  8. Re-collect and confirm. Reset the log file, run another window, parse again. The query you just indexed should drop off the top of the digest.

Common pitfalls

  • long_query_time = 0 left on for hours generates gigabytes of log and starts impacting query performance. Always set a timer to revert.
  • A slow query log without rotation fills the disk. The first symptom is the daemon refusing to write, then refusing connections. Configure logrotate before turning the log on.
  • log_output = TABLE writes to mysql.slow_log, which is a CSV-engine table — queries against it are slow, and it does not work with pt-query-digest. Stick to file unless you have a specific reason.
  • A digest run on a half-rotated log file gives misleading totals — parse a snapshot copy, not the live file.
  • The percona toolkit’s pt-query-digest reads from binlog and processlist too; use it on processlist (pt-query-digest --processlist h=localhost) for live-query sampling without restarting anything.

In the engagements we run, the slow query log is on by default with long_query_time = 0.5, a nightly pt-query-digest produces a Markdown digest mailed to the operator on-call, and any query that enters the top 10 for two consecutive weeks gets a ticket. We carry that under Managed Operations so performance regressions surface as a list, not as a 4 a.m. page.