What it does
With log_output = TABLE, MySQL writes the slow query log to the mysql.slow_log table instead of a file. That's common on RDS and Aurora, where you can't read the server's files. pt-query-digest, the usual tool for summarizing a slow log, only reads files.
slow_log_digest.sh reads the last N minutes of mysql.slow_log and writes them out in the slow-log file format. Then it runs pt-query-digest on that file:
slow_<timestamp>-<N>min.log: the rebuilt slow logdigest_<timestamp>-<N>min.txt: the pt-query-digest report, every statement ranked by total time
#!/usr/bin/env bash
# slow_log_digest.sh: run pt-query-digest on the last N minutes of mysql.slow_log (log_output=TABLE)
# Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
# https://hashjoin.com/kb/mysql/pt-query-digest-rds-slow-log-table/
#
# Usage: slow_log_digest.sh MINUTES [--extract-only] [-- MYSQL_CLIENT_OPTIONS...]
#
# MINUTES how far back to read mysql.slow_log
# --extract-only write the slow-log file and stop (run pt-query-digest elsewhere)
# -- ... passed to the mysql client: --defaults-file=..., --host=..., etc.
#
# Writes slow_<timestamp>-<N>min.log (the rows rebuilt in slow-log file format) and
# digest_<timestamp>-<N>min.txt (the pt-query-digest report) to $OUT_DIR (default: .).
# PT_QUERY_DIGEST names the pt-query-digest command (default: pt-query-digest).
#
# Every 5 minutes, overlapping a little so nothing falls between runs:
# */5 * * * * cd /opt/slowlog && ./slow_log_digest.sh 7 -- --defaults-file=.my.cnf --host=mydb.xxxx.rds.amazonaws.com
set -euo pipefail
MIN="${1:?usage: $0 MINUTES [--extract-only] [-- mysql options]}"; shift
case "$MIN" in ''|*[!0-9]*) echo "MINUTES must be a whole number" >&2; exit 2 ;; esac
EXTRACT_ONLY=no
while [ $# -gt 0 ]; do
case "$1" in
--extract-only) EXTRACT_ONLY=yes; shift ;;
--) shift; break ;;
*) echo "usage: $0 MINUTES [--extract-only] [-- mysql options]" >&2; exit 2 ;;
esac
done
OUT_DIR="${OUT_DIR:-.}"
STAMP=$(date +%Y%m%d_%H%M%S)
LOG="$OUT_DIR/slow_${STAMP}-${MIN}min.log"
REP="$OUT_DIR/digest_${STAMP}-${MIN}min.txt"
# One slow-log entry per row, in the format pt-query-digest parses. query_time and lock_time
# are TIME(6). The seconds are built from their parts with all six decimals: TIME_TO_SEC()
# drops the fraction, and dividing MICROSECOND() by 1000000 rounds to four places, so a
# 0.07 ms query would read 0.0001 or 0. The session runs in UTC so the "# Time:" lines can
# say so.
mysql "$@" --batch --raw --skip-column-names -e "
SET time_zone = '+00:00';
SELECT CONCAT(
'# Time: ', DATE_FORMAT(start_time, '%Y-%m-%dT%H:%i:%s.%fZ'), '\n',
'# User@Host: ', user_host, ' Id: ', thread_id, '\n',
'# Query_time: ', HOUR(query_time) * 3600 + MINUTE(query_time) * 60 + SECOND(query_time),
'.', LPAD(MICROSECOND(query_time), 6, '0'),
' Lock_time: ', HOUR(lock_time) * 3600 + MINUTE(lock_time) * 60 + SECOND(lock_time),
'.', LPAD(MICROSECOND(lock_time), 6, '0'),
' Rows_sent: ', rows_sent, ' Rows_examined: ', rows_examined, '\n',
IF(db IS NULL OR db = '', '', CONCAT('use ', db, ';\n')),
'SET timestamp=', FLOOR(UNIX_TIMESTAMP(start_time)), ';\n',
TRIM(TRAILING ';' FROM CONVERT(sql_text USING utf8mb4)), ';')
FROM mysql.slow_log
WHERE start_time >= NOW() - INTERVAL ${MIN} MINUTE
ORDER BY start_time" > "$LOG"
echo "$(date): $(grep -c '^# Time: ' "$LOG" || true) slow-log entries in the last ${MIN} minutes -> $LOG"
[ "$EXTRACT_ONLY" = yes ] && exit 0
${PT_QUERY_DIGEST:-pt-query-digest} --limit 100% "$LOG" > "$REP"
echo "$(date): report -> $REP"curl -O https://hashjoin.com/kb/mysql/pt-query-digest-rds-slow-log-table/slow_log_digest.sh
Usage
By hand, for the last 30 minutes:
./slow_log_digest.sh 30 -- --defaults-file=~/.my.cnf --host=mydb.xxxx.us-east-1.rds.amazonaws.com
From cron, every 5 minutes, reading 7 so consecutive runs overlap a little:
*/5 * * * * cd /opt/slowlog && ./slow_log_digest.sh 7 -- --defaults-file=.my.cnf --host=mydb.xxxx.rds.amazonaws.com
--extract-only writes the slow-log file and stops, so you can copy it to wherever pt-query-digest is installed. PT_QUERY_DIGEST names the command if it isn't on the PATH. With Docker, for example, PT_QUERY_DIGEST="docker run --rm -i -v $PWD:$PWD -w $PWD percona/percona-toolkit:3.7 pt-query-digest".
Reading the output
From the lab: log_output = TABLE, long_query_time = 0, then 4 connections running one indexed SELECT 500 times each, plus some light traffic. The first entry of the rebuilt slow log:
# Time: 2026-12-04T19:18:18.198696Z
# User@Host: root[root] @ localhost [] Id: 235
# Query_time: 0.001425 Lock_time: 0.000000 Rows_sent: 0 Rows_examined: 0
SET timestamp=1796411898;
TRUNCATE mysql.slow_log;
The indexed SELECT's entries look the same, with timings like # Query_time: 0.000201 Lock_time: 0.000001 Rows_sent: 20 Rows_examined: 40.
And the profile pt-query-digest made from the file:
# Rank Query ID Response time Calls R/Call V/M
# ==== =================================== ============= ===== ====== ====
# 1 0xB3DB7544C669C145EC2F1EBC228A661D 0.0695 92.6% 2000 0.0000 0.00 SELECT kblab.items
# 2 0x787FAD062AB62D9DC2740C36E5A6720E 0.0024 3.2% 100 0.0000 0.00 SELECT kblab.items
# 3 0xCC639FA0688B141139CC8FBB0C0CB116 0.0014 1.9% 100 0.0000 0.00 SELECT kblab.items
# 4 0xD0479606FA37DEF7B324A65C68E06068 0.0014 1.9% 1 0.0014 0.00 TRUNCATE
The precision matters. With timings rounded to four decimals, the same 2,000 calls added up to 0.0053 s instead of 0.0695 s, and the whole run to 7 ms instead of 75 ms. The fast, frequent statement that should top the report was undercounted more than tenfold.
Gotchas
- Keep all six decimals.
query_timeandlock_timeareTIME(6).TIME_TO_SEC()drops the fraction, so every sub-second query showsQuery_time: 0and the report ranks them all as free. The 2017 version of this script had exactly that bug. AddingMICROSECOND(query_time) / 1000000back isn't enough either: MySQL rounds that division to four decimal places, so a 0.07 ms query still reads0.0001(the lab caught this). This script builds the number from its parts. - The table is a CSV table, so every query against it reads the whole thing. Reading a few minutes every 5 minutes is fine; don't point dashboards at it.
- RDS can rotate the table.
mysql.rds_rotate_slow_logmoves its rows intomysql.slow_log_backup, and anything rotated out before a run isn't seen. long_query_timedecides what you'll see. At 10 seconds you'll only see the long statements. To find a fast statement that runs too often, lower it briefly, or rank statements from performance_schema instead: MySQL CPU at 90% but the slow query log is empty.
What it reads
Related
- MySQL CPU at 90% but the slow query log is empty
- AWR for MySQL: snapshots of performance_schema statement digests
Running this fleet-wide, by hand?
HASHJOIN builds the control plane that runs upgrades, failovers and repairs like this one across every host, with a lock per unit, a drain on Ctrl-C and a log you can read at 3 a.m.
New fixes and field notes by email, about once a month.