KB · MySQL · How-to

AWR for MySQL: snapshots of performance_schema statement digests

MySQL · How-to · Verified on MySQL 8.0 and 8.4 · Updated 2026-12-04

What this gives you

MySQL already counts every statement it runs: performance_schema.events_statements_summary_by_digest keeps one row per normalized statement (literals replaced with ?) with its calls, total time, rows examined and rows sent. But those are running totals since the server started. They can't tell you what ran between 07:55 and 08:10 this morning, when the CPU went to 90%.

These scripts copy that table into an awr schema every 5 minutes, the way Oracle's AWR keeps snapshots, and report on the difference between snapshots:

If you pass in the host's CPU at each snapshot (awr_snap.sh reads it from CloudWatch for RDS and Aurora), each window comes with the CPU it had.

How it works

Each snapshot copies the digest table's counters as they are. The awr.digest_delta view subtracts each snapshot from the one before it, so the reports work on what happened in between. Nothing is reset: other tools that read the same table (the sys schema's statement_analysis, PMM, your own dashboards) keep their numbers.

When the counters do restart (a server restart, or someone truncating the table), a statement's count goes down instead of up, or it's missing from the earlier snapshot. The view treats the current numbers as the delta then, and marks the row new_or_reset (also set the first time a statement is seen).

Set up

Create the schema once, as a user that can create databases:

mysql < awr_setup.sql

The snapshot user needs to read performance_schema and write to awr:

CREATE USER 'awr'@'%' IDENTIFIED BY '...';
GRANT SELECT ON performance_schema.* TO 'awr'@'%';
GRANT SELECT, INSERT, UPDATE, DELETE ON awr.* TO 'awr'@'%';

Check that statement digests are being collected. They are by default on MySQL 8.0 and later; on RDS, Performance Schema itself has to be turned on in the parameter group:

SELECT * FROM performance_schema.setup_consumers WHERE NAME = 'statements_digest';

Take snapshots

From cron, every 5 minutes. With --rds-instance it records the instance's CPU too; with --keep-days it deletes old snapshots:

*/5 * * * * /opt/awr/awr_snap.sh --rds-instance mydb --keep-days 14 -- --defaults-file=/opt/awr/.my.cnf --host=mydb.xxxx.us-east-1.rds.amazonaws.com >> /var/log/awr_snap.log 2>&1

Or by hand, with whatever CPU number you have:

mysql -e "set @cpu = 91.5; source awr_snap.sql"
awr_setup.sqlMIT · Download ·
-- awr_setup.sql: create the awr schema that keeps snapshots of MySQL statement digests
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/
--
-- Usage: mysql < awr_setup.sql        (safe to run again; it never drops anything)
--
-- awr.snap          one row per snapshot: when, the host's CPU if you pass it, digest-table health
-- awr.digest_stat   the cumulative counters of every digest at that snapshot
-- awr.digest_text   the normalized statement text, stored once per digest
-- awr.snap_interval each snapshot with the one before it and the seconds between them
-- awr.digest_delta  what each digest did between consecutive snapshots: the numbers you report on

CREATE DATABASE IF NOT EXISTS awr;

CREATE TABLE IF NOT EXISTS awr.snap (
  snap_id      INT UNSIGNED  NOT NULL AUTO_INCREMENT PRIMARY KEY,
  taken_at     DATETIME(6)   NOT NULL,
  cpu_pct      DECIMAL(5,2)  NULL,        -- from your monitoring (CloudWatch, node exporter); NULL if not passed
  digests      INT UNSIGNED  NOT NULL DEFAULT 0,
  digest_lost  BIGINT UNSIGNED NULL,      -- Performance_schema_digest_lost: statements that found the digest table full
  KEY snap_taken (taken_at)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS awr.digest_stat (
  snap_id                     INT UNSIGNED    NOT NULL,
  schema_name                 VARCHAR(64)     NOT NULL DEFAULT '',  -- '' = no default database
  digest                      VARCHAR(64)     NOT NULL DEFAULT '',  -- '' = the catch-all row used once the digest table is full
  count_star                  BIGINT UNSIGNED NOT NULL,
  sum_timer_wait              BIGINT UNSIGNED NOT NULL,             -- picoseconds
  sum_lock_time               BIGINT UNSIGNED NOT NULL,
  sum_errors                  BIGINT UNSIGNED NOT NULL,
  sum_rows_sent               BIGINT UNSIGNED NOT NULL,
  sum_rows_examined           BIGINT UNSIGNED NOT NULL,
  sum_rows_affected           BIGINT UNSIGNED NOT NULL,
  sum_created_tmp_disk_tables BIGINT UNSIGNED NOT NULL,
  sum_no_index_used           BIGINT UNSIGNED NOT NULL,
  first_seen                  DATETIME(6)     NULL,
  last_seen                   DATETIME(6)     NULL,
  PRIMARY KEY (snap_id, schema_name, digest),
  KEY digest_stat_digest (digest)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS awr.digest_text (
  digest        VARCHAR(64)  NOT NULL PRIMARY KEY,
  digest_text   LONGTEXT     NULL,
  first_snap_id INT UNSIGNED NOT NULL
) ENGINE=InnoDB;

CREATE OR REPLACE VIEW awr.snap_interval AS
SELECT s.snap_id,
       p.snap_id AS prev_snap_id,
       s.taken_at,
       TIMESTAMPDIFF(MICROSECOND, p.taken_at, s.taken_at) / 1000000 AS interval_sec,
       s.cpu_pct
FROM awr.snap s
JOIN awr.snap p ON p.snap_id = (SELECT MAX(x.snap_id) FROM awr.snap x WHERE x.snap_id < s.snap_id);

-- The counters only ever grow, except when someone truncates the digest table or the server
-- restarts. A digest with no row in the previous snapshot, or with a smaller count than before,
-- started counting again since then, so its current values are the delta.
CREATE OR REPLACE VIEW awr.digest_delta AS
SELECT i.snap_id, i.prev_snap_id, i.taken_at, i.interval_sec, i.cpu_pct,
       c.schema_name, c.digest,
       IF(p.digest IS NULL OR c.count_star < p.count_star, 1, 0) AS new_or_reset,
       c.count_star        - IF(p.digest IS NULL OR c.count_star < p.count_star, 0, p.count_star)        AS calls,
       c.sum_timer_wait    - IF(p.digest IS NULL OR c.count_star < p.count_star, 0, p.sum_timer_wait)    AS time_ps,
       c.sum_lock_time     - IF(p.digest IS NULL OR c.count_star < p.count_star, 0, p.sum_lock_time)     AS lock_ps,
       c.sum_errors        - IF(p.digest IS NULL OR c.count_star < p.count_star, 0, p.sum_errors)        AS errors,
       c.sum_rows_sent     - IF(p.digest IS NULL OR c.count_star < p.count_star, 0, p.sum_rows_sent)     AS rows_sent,
       c.sum_rows_examined - IF(p.digest IS NULL OR c.count_star < p.count_star, 0, p.sum_rows_examined) AS rows_examined,
       c.sum_rows_affected - IF(p.digest IS NULL OR c.count_star < p.count_star, 0, p.sum_rows_affected) AS rows_affected,
       c.sum_created_tmp_disk_tables - IF(p.digest IS NULL OR c.count_star < p.count_star, 0, p.sum_created_tmp_disk_tables) AS tmp_disk_tables,
       c.sum_no_index_used - IF(p.digest IS NULL OR c.count_star < p.count_star, 0, p.sum_no_index_used) AS no_index_used
FROM awr.snap_interval i
JOIN awr.digest_stat c ON c.snap_id = i.snap_id
LEFT JOIN awr.digest_stat p ON p.snap_id = i.prev_snap_id AND p.schema_name = c.schema_name AND p.digest = c.digest;

curl -O https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/awr_setup.sql

awr_snap.sqlMIT · Download ·
-- awr_snap.sql: take one snapshot of performance_schema statement digests into the awr schema
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/
--
-- Usage: mysql -e "source awr_snap.sql"
--        mysql -e "set @cpu = 91.5; source awr_snap.sql"     (record the host's CPU % too)
--
-- Reads events_statements_summary_by_digest and leaves it alone: no TRUNCATE, so sys schema
-- views and other tools that read the same table keep their numbers. awr.digest_delta works
-- out what happened between snapshots.

SET @cpu = NULLIF(@cpu, '');

INSERT INTO awr.snap (taken_at, cpu_pct, digest_lost)
VALUES (NOW(6), @cpu,
        (SELECT VARIABLE_VALUE FROM performance_schema.global_status
         WHERE VARIABLE_NAME = 'Performance_schema_digest_lost'));

SET @sid = LAST_INSERT_ID();

INSERT INTO awr.digest_stat
  (snap_id, schema_name, digest, count_star, sum_timer_wait, sum_lock_time, sum_errors,
   sum_rows_sent, sum_rows_examined, sum_rows_affected, sum_created_tmp_disk_tables,
   sum_no_index_used, first_seen, last_seen)
SELECT @sid, IFNULL(SCHEMA_NAME, ''), IFNULL(DIGEST, ''), COUNT_STAR, SUM_TIMER_WAIT, SUM_LOCK_TIME,
       SUM_ERRORS, SUM_ROWS_SENT, SUM_ROWS_EXAMINED, SUM_ROWS_AFFECTED, SUM_CREATED_TMP_DISK_TABLES,
       SUM_NO_INDEX_USED, FIRST_SEEN, LAST_SEEN
FROM performance_schema.events_statements_summary_by_digest;

INSERT INTO awr.digest_text (digest, digest_text, first_snap_id)
SELECT DIGEST, MAX(DIGEST_TEXT), @sid
FROM performance_schema.events_statements_summary_by_digest
WHERE DIGEST IS NOT NULL
GROUP BY DIGEST
ON DUPLICATE KEY UPDATE first_snap_id = awr.digest_text.first_snap_id;

UPDATE awr.snap
SET digests = (SELECT COUNT(*) FROM awr.digest_stat WHERE snap_id = @sid)
WHERE snap_id = @sid;

SELECT snap_id, taken_at, cpu_pct, digests, digest_lost FROM awr.snap WHERE snap_id = @sid;

curl -O https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/awr_snap.sql

awr_snap.shMIT · Download ·
#!/usr/bin/env bash
# awr_snap.sh: cron wrapper for awr_snap.sql: one snapshot, optional RDS CPU, optional purge
# Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
# https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/
#
# Usage: awr_snap.sh [--rds-instance ID] [--keep-days N] [-- MYSQL_CLIENT_OPTIONS...]
#
#   --rds-instance ID  also record the instance's CPU (CloudWatch CPUUtilization, the highest
#                      1-minute value of the last 5 minutes); needs the aws CLI
#   --keep-days N      afterwards, delete snapshots older than N days (awr_purge.sql)
#   -- ...             passed to the mysql client: --defaults-file=..., --host=..., etc.
#
# Every 5 minutes, from cron:
#   */5 * * * * /opt/awr/awr_snap.sh --rds-instance mydb --keep-days 14 -- --defaults-file=/opt/awr/.my.cnf --host=mydb.xxxx.us-east-1.rds.amazonaws.com >> /var/log/awr_snap.log 2>&1
set -euo pipefail

DIR="$(cd "$(dirname "$0")" && pwd)"
RDS=""; KEEP=""
while [ $# -gt 0 ]; do
  case "$1" in
    --rds-instance) RDS="$2"; shift 2 ;;
    --keep-days)    KEEP="$2"; shift 2 ;;
    --)             shift; break ;;
    *)              echo "usage: $0 [--rds-instance ID] [--keep-days N] [-- mysql options]" >&2; exit 2 ;;
  esac
done

CPU=""
if [ -n "$RDS" ]; then
  # GNU date on Linux, BSD date on a Mac.
  START=$(date -u -d '5 minutes ago' +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-5M +%Y-%m-%dT%H:%M:%SZ)
  END=$(date -u +%Y-%m-%dT%H:%M:%SZ)
  CPU=$(aws cloudwatch get-metric-statistics --namespace AWS/RDS --metric-name CPUUtilization \
          --dimensions Name=DBInstanceIdentifier,Value="$RDS" \
          --start-time "$START" --end-time "$END" --period 60 --statistics Maximum \
          --query 'max(Datapoints[].Maximum)' --output text 2>/dev/null || true)
  # No datapoint yet comes back as "None": record no CPU rather than fail the snapshot.
  case "$CPU" in ''|None|*[!0-9.]*) echo "$(date): no CPU datapoint for $RDS" >&2; CPU="" ;; esac
fi

echo "$(date): snapshot${CPU:+ (cpu $CPU%)}"
mysql "$@" -t -e "set @cpu = '${CPU}'; source $DIR/awr_snap.sql;"

if [ -n "$KEEP" ]; then
  mysql "$@" -t -e "set @keep_days = ${KEEP}; source $DIR/awr_purge.sql;"
fi

curl -O https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/awr_snap.sh

awr_top.sqlMIT · Download ·
-- awr_top.sql: the statements that used the most database time between two points in time
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/
--
-- Usage: mysql -t -e "set @from = '2026-12-04 07:55', @to = '2026-12-04 08:10'; source awr_top.sql"
--
-- Counts every snapshot interval that ends after @from and no later than @to.
-- aas (average active sessions) = statement time / wall-clock time: 4.0 means that statement
-- kept four sessions busy, on average, for the whole window.

SELECT COUNT(*), SUM(interval_sec), MAX(cpu_pct)
INTO @snaps, @secs, @max_cpu
FROM awr.snap_interval
WHERE taken_at > @from AND taken_at <= @to;

SELECT @from AS window_from, @to AS window_to, @snaps AS intervals,
       ROUND(@secs) AS seconds, ROUND(@max_cpu, 1) AS max_cpu_pct;

SELECT d.schema_name,
       LEFT(d.digest, 12)                                          AS digest,
       SUM(d.calls)                                                AS calls,
       ROUND(SUM(d.calls) / @secs, 1)                              AS per_sec,
       ROUND(SUM(d.time_ps) / 1e12, 1)                             AS total_sec,
       ROUND(SUM(d.time_ps) / 1e12 / @secs, 2)                     AS aas,
       ROUND(SUM(d.time_ps) / NULLIF(SUM(d.calls), 0) / 1e9, 3)    AS avg_ms,
       ROUND(SUM(d.rows_examined) / NULLIF(SUM(d.calls), 0))       AS exam_per_call,
       ROUND(SUM(d.rows_sent) / NULLIF(SUM(d.calls), 0))           AS sent_per_call,
       LEFT(REPLACE(MAX(t.digest_text), '\n', ' '), 70)            AS statement
FROM awr.digest_delta d
LEFT JOIN awr.digest_text t ON t.digest = d.digest
WHERE d.taken_at > @from AND d.taken_at <= @to
GROUP BY d.schema_name, d.digest
HAVING SUM(d.calls) > 0
ORDER BY SUM(d.time_ps) DESC
LIMIT 15;

curl -O https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/awr_top.sql

awr_diff.sqlMIT · Download ·
-- awr_diff.sql: what changed between a bad window and a normal one, statement by statement
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/
--
-- Usage: mysql -t -e "set @a_from = '2026-12-04 07:55', @a_to = '2026-12-04 08:10',
--                         @b_from = '2026-12-04 02:30', @b_to = '2026-12-04 02:45';
--                     source awr_diff.sql"
--
-- A is the window you're investigating (the CPU spike); B is a normal one to compare with.
-- Rates are per second so windows of different lengths compare fairly. Sorted by how much
-- more database time (aas) a statement used in A than in B: the top rows are what the spike
-- added, whether by running more often (calls/s) or by getting slower (avg_ms).

SELECT SUM(interval_sec), MAX(cpu_pct) INTO @a_secs, @a_cpu
FROM awr.snap_interval WHERE taken_at > @a_from AND taken_at <= @a_to;
SELECT SUM(interval_sec), MAX(cpu_pct) INTO @b_secs, @b_cpu
FROM awr.snap_interval WHERE taken_at > @b_from AND taken_at <= @b_to;

SELECT 'A' AS w, @a_from AS window_from, @a_to AS window_to, ROUND(@a_secs) AS seconds, ROUND(@a_cpu, 1) AS max_cpu_pct
UNION ALL
SELECT 'B', @b_from, @b_to, ROUND(@b_secs), ROUND(@b_cpu, 1);

SELECT a.schema_name,
       LEFT(a.digest, 12)                                    AS digest,
       ROUND(a.calls / @a_secs, 1)                           AS a_per_sec,
       ROUND(IFNULL(b.calls, 0) / @b_secs, 1)                AS b_per_sec,
       ROUND(a.time_ps / 1e12 / @a_secs, 2)                  AS a_aas,
       ROUND(IFNULL(b.time_ps, 0) / 1e12 / @b_secs, 2)       AS b_aas,
       ROUND(a.time_ps / NULLIF(a.calls, 0) / 1e9, 3)        AS a_avg_ms,
       ROUND(b.time_ps / NULLIF(b.calls, 0) / 1e9, 3)        AS b_avg_ms,
       LEFT(REPLACE(t.digest_text, '\n', ' '), 60)           AS statement
FROM (SELECT schema_name, digest, SUM(calls) AS calls, SUM(time_ps) AS time_ps
      FROM awr.digest_delta WHERE taken_at > @a_from AND taken_at <= @a_to
      GROUP BY schema_name, digest) a
LEFT JOIN (SELECT schema_name, digest, SUM(calls) AS calls, SUM(time_ps) AS time_ps
           FROM awr.digest_delta WHERE taken_at > @b_from AND taken_at <= @b_to
           GROUP BY schema_name, digest) b
       ON b.schema_name = a.schema_name AND b.digest = a.digest
LEFT JOIN awr.digest_text t ON t.digest = a.digest
WHERE a.calls > 0
ORDER BY a.time_ps / 1e12 / @a_secs - IFNULL(b.time_ps, 0) / 1e12 / @b_secs DESC
LIMIT 15;

curl -O https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/awr_diff.sql

awr_digest.sqlMIT · Download ·
-- awr_digest.sql: one statement's history, snapshot by snapshot
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/
--
-- Usage: mysql -t -e "set @digest = '9f3c2a1b7e44'; source awr_digest.sql"
--
-- @digest can be the first characters of the digest, as awr_top.sql and awr_diff.sql show it.

SELECT digest, digest_text FROM awr.digest_text WHERE digest LIKE CONCAT(@digest, '%') LIMIT 2;

SELECT d.taken_at,
       d.cpu_pct,
       d.schema_name,
       d.calls,
       ROUND(d.calls / d.interval_sec, 1)                    AS per_sec,
       ROUND(d.time_ps / 1e12 / d.interval_sec, 2)           AS aas,
       ROUND(d.time_ps / NULLIF(d.calls, 0) / 1e9, 3)        AS avg_ms,
       ROUND(d.rows_examined / NULLIF(d.calls, 0))           AS exam_per_call,
       ROUND(d.rows_sent / NULLIF(d.calls, 0))               AS sent_per_call,
       d.new_or_reset
FROM awr.digest_delta d
WHERE d.digest LIKE CONCAT(@digest, '%')
  AND d.calls > 0
ORDER BY d.taken_at;

curl -O https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/awr_digest.sql

awr_purge.sqlMIT · Download ·
-- awr_purge.sql: delete awr snapshots older than @keep_days days
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/
--
-- Usage: mysql -e "set @keep_days = 14; source awr_purge.sql"

SET @keep_days = IFNULL(@keep_days, 14);
SET @cutoff = NOW(6) - INTERVAL @keep_days DAY;

-- Single-table deletes: the multi-table form (DELETE d FROM awr.digest_stat d JOIN ...) fails with
-- "No database selected" when the session has no default database, as from cron.
DELETE FROM awr.digest_stat WHERE snap_id IN (SELECT snap_id FROM awr.snap WHERE taken_at < @cutoff);
DELETE FROM awr.snap WHERE taken_at < @cutoff;
DELETE FROM awr.digest_text
WHERE NOT EXISTS (SELECT 1 FROM awr.digest_stat d WHERE d.digest = awr.digest_text.digest);

SELECT COUNT(*) AS snapshots_kept, MIN(taken_at) AS oldest, MAX(taken_at) AS newest FROM awr.snap;

curl -O https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/awr_purge.sql

Report

All three reports take user variables and print tables; run them with mysql -t.

Top statements in a window, by database time:

mysql -t -e "set @from = '2026-12-04 07:55', @to = '2026-12-04 08:10'; source awr_top.sql"

aas is average active sessions: the statement's total time divided by the window's length. A statement with aas 4.0 kept four sessions busy for the whole window, which on a 4-vCPU host is all of it.

A bad window against a normal one. A is the window you're investigating, B the normal one:

mysql -t -e "set @a_from = '2026-12-04 07:55', @a_to = '2026-12-04 08:10',
                 @b_from = '2026-12-04 02:30', @b_to = '2026-12-04 02:45';
             source awr_diff.sql"

Rates are per second, so the windows can be different lengths. The rows are sorted by how much more database time a statement used in A than in B. The columns tell you why: it ran more often (a_per_sec against b_per_sec), or each call got slower (a_avg_ms against b_avg_ms).

One statement's history, by the digest prefix the other reports print:

mysql -t -e "set @digest = '9f3c2a1b7e44'; source awr_digest.sql"

Reading the output

From the lab: a 4-second baseline of light traffic, then 16 connections running one cheap, indexed SELECT 4,000 times each. Snapshots were taken before, between and after, with CPU recorded as 12% and 91%. awr_top.sql for the spike window (columns trimmed):

+-------------+--------------+-------+---------+-----------+------+--------+---------------+--------------------------------------+
| schema_name | digest       | calls | per_sec | total_sec | aas  | avg_ms | exam_per_call | statement                            |
+-------------+--------------+-------+---------+-----------+------+--------+---------------+--------------------------------------+
| kblab       | 2c589e59cbb7 | 63959 | 15306.7 |       4.6 | 1.11 |  0.073 |            40 | SELECT `id` , `project_id` , `par... |
|             | 245076937d54 |     1 |     0.2 |         0 |    0 |  1.585 |            20 | INSERT INTO `awr` . `digest_stat`... |
| kblab       | 44e35cee979b |    16 |     3.8 |         0 |    0 |  0.086 |             1 | SELECT @@`version_comment` LIMIT ?   |

At 0.073 ms a call, no single run comes near the slow log's threshold. But 15,000 calls a second add up to 1.11 average active sessions: on average, more than one session was busy with that one statement for the whole window. The snapshots' own statements show up too, at almost no cost.

awr_diff.sql with the spike as A and the baseline as B puts the same statement first, at 15,306.7 calls a second against 0.0 in the baseline. awr_digest.sql shows its history one snapshot at a time, with the CPU recorded next to each.

Gotchas

What it reads

performance_schema.events_statements_summary_by_digest performance_schema.global_status

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.