Is it slow, or is it just 9 a.m.? An hour-of-day baseline for performance_schema digests in plain SQL
Most "is this query slow?" checks compare against a daily average or a fixed threshold. A database that's busy at 09:00 and quiet at 03:00 has an average that describes neither, so you either get alerts every busy morning or miss a real regression overnight.
A better comparison is each statement's time per call against its median for the same hour of the day over the previous 14 days. On MySQL 8 it takes three pieces of SQL on top of performance_schema's digest table, plus the event scheduler.
1. Every hour, copy the cumulative counters
CREATE TABLE stmt_snap (
taken_at DATETIME NOT NULL, -- UTC, top of the hour
schema_name VARCHAR(64) NOT NULL,
digest VARCHAR(64) NOT NULL,
calls BIGINT UNSIGNED NOT NULL,
total_ps BIGINT UNSIGNED NOT NULL, -- picoseconds
first_seen DATETIME(6) NOT NULL,
PRIMARY KEY (schema_name, digest, taken_at)
);
CREATE EVENT stmt_snap_hourly
ON SCHEDULE EVERY 1 HOUR
STARTS DATE_FORMAT(NOW() + INTERVAL 1 HOUR, '%Y-%m-%d %H:00:05')
DO
INSERT IGNORE INTO stmt_snap
SELECT DATE_FORMAT(UTC_TIMESTAMP(), '%Y-%m-%d %H:00:00'),
IFNULL(SCHEMA_NAME, ''), DIGEST, COUNT_STAR, SUM_TIMER_WAIT, FIRST_SEEN
FROM performance_schema.events_statements_summary_by_digest
WHERE DIGEST IS NOT NULL;
The event scheduler is on by default in 8.0+ (SELECT @@event_scheduler;). The event's definer needs SELECT on performance_schema. FIRST_SEEN is kept on purpose: it's how step 2 spots a row that was reset or evicted and came back.
2. Turn the snapshots into one row per statement per hour
CREATE TABLE stmt_hourly (
hour_start DATETIME NOT NULL, -- UTC
schema_name VARCHAR(64) NOT NULL,
digest VARCHAR(64) NOT NULL,
calls BIGINT UNSIGNED NOT NULL,
total_ms DOUBLE NOT NULL,
PRIMARY KEY (schema_name, digest, hour_start)
);
INSERT IGNORE INTO stmt_hourly
SELECT prev_at, schema_name, digest,
calls - prev_calls,
(total_ps - prev_ps) / 1e9 -- picoseconds to ms
FROM (SELECT s.*,
LAG(taken_at) OVER w AS prev_at,
LAG(calls) OVER w AS prev_calls,
LAG(total_ps) OVER w AS prev_ps,
LAG(first_seen) OVER w AS prev_first
FROM stmt_snap s
WINDOW w AS (PARTITION BY schema_name, digest ORDER BY taken_at)) d
WHERE taken_at = prev_at + INTERVAL 1 HOUR -- consecutive snapshots only
AND first_seen = prev_first -- same row, no reset or eviction in between
AND calls > prev_calls -- it ran in that hour
AND total_ps >= prev_ps;
3. Flag the last full hour against its usual for that hour of the day
WITH h AS (
SELECT schema_name, digest, hour_start, calls, total_ms / calls AS ms_per_call,
HOUR(CONVERT_TZ(hour_start, 'UTC', 'America/Denver')) AS hod -- your users' time zone
FROM stmt_hourly
), ranked AS (
SELECT schema_name, digest, hod, ms_per_call,
ROW_NUMBER() OVER p AS rn,
COUNT(*) OVER p AS n
FROM h
WHERE hour_start >= DATE(UTC_TIMESTAMP()) - INTERVAL 14 DAY
AND hour_start < DATE(UTC_TIMESTAMP())
WINDOW p AS (PARTITION BY schema_name, digest, hod ORDER BY ms_per_call)
), base AS ( -- MySQL has no PERCENTILE_CONT, so rank and pick
SELECT schema_name, digest, hod,
AVG(CASE WHEN rn IN (FLOOR((n + 1) / 2), CEIL((n + 1) / 2)) THEN ms_per_call END) AS median_ms,
MIN(CASE WHEN rn >= CEIL(0.9 * n) THEN ms_per_call END) AS p90_ms,
MAX(n) AS samples
FROM ranked
GROUP BY schema_name, digest, hod
)
SELECT h.schema_name,
LEFT(d.DIGEST_TEXT, 80) AS statement,
ROUND(h.ms_per_call, 1) AS ms_now,
ROUND(b.median_ms, 1) AS usual_ms,
ROUND(h.ms_per_call / b.median_ms, 1) AS times_usual,
ROUND((h.ms_per_call - b.median_ms) * h.calls / 1000) AS extra_s
FROM h
JOIN base b USING (schema_name, digest, hod)
LEFT JOIN performance_schema.events_statements_summary_by_digest d
ON d.DIGEST = h.digest AND IFNULL(d.SCHEMA_NAME, '') = h.schema_name
WHERE h.hour_start = DATE_FORMAT(UTC_TIMESTAMP() - INTERVAL 1 HOUR, '%Y-%m-%d %H:00:00')
AND b.samples >= 7 -- enough history to trust
AND h.ms_per_call > GREATEST(1.5 * b.median_ms, b.p90_ms) -- well above its usual range
AND (h.ms_per_call - b.median_ms) * h.calls >= 60000 -- and it cost at least a minute
ORDER BY extra_s DESC;
Rank by the extra seconds, not by the ratio. A statement 10x slower that adds one second an hour matters less than one 2x slower that adds an hour of server time.
A few gotchas
- Time zones. Store UTC, but compute the hour of the day in the zone your workload follows. CONVERT_TZ with a named zone returns NULL until the time zone tables are loaded (mysql_tzinfo_to_sql), and a fixed offset like '-07:00' breaks at every daylight-saving change.
- The digest table fills up. It holds performance_schema_digests_size rows. Once it's full, new statements land in the row with a NULL digest, and Performance_schema_digest_lost goes up. If that row is busy, raise the size (restart needed).
- Resets. A restart or TRUNCATE of the summary table zeroes everything. The FIRST_SEEN check in step 2 skips those hours instead of reading them as negative or huge.
- QUANTILE_95 won't do this for you. The digest table's quantile columns cover everything since the last reset, so they can't tell you about this hour against the same hour last week.
- Median, not mean. One bad hour shouldn't redefine normal. MySQL has no PERCENTILE_CONT, which is why step 3 ranks the rows and picks the middle one.
- Weekly cycles. If Monday's batch is different, compare with the same hour last week too.
- Normal isn't good. A baseline tells you what's usual, not what's acceptable. A server that's been slow for a month has a slow baseline, so pair it with a target.
- Housekeeping. Keep a couple of days of stmt_snap and five or six weeks of stmt_hourly (another event can do the DELETEs).
How do you baseline yours? Same hour last week, a rolling window, or something smarter?
Brett Rosenblatt is a DBA and performance engineer and a co-founder of Bandlei, which makes ReinDB, a read-only performance monitor for MySQL, PostgreSQL and other databases. This post is adapted from chapter 12 of his free tuning guide, Rein In Your Database.