Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Last active January 28, 2018 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahemoff/968016ce0dbab2172258776943749602 to your computer and use it in GitHub Desktop.
Save mahemoff/968016ce0dbab2172258776943749602 to your computer and use it in GitHub Desktop.
MySQL one-liner for monitoring long queries on the console

MOTIVATION

The usual advice for monitoring MySQL is to run SHOW PROCESSLIST. However, that's not ordered or filtered, and the entire text of queries is shown. For long queries, e.g. batch-type queries identifying specific IDs, can be very long and end up flooding your terminal, making the output troublesome to comprehend.

Fortunately we can query the state as if it were a regular table. The query here does that. It ignores sleeping processes (common if clients are using connection pools), filters slow processes (those began over 5 seconds), and truncates the query to your defined length.

+---------+--------+------------+-------------------+---------+------+----------+------------------------------------------------------------------------------------------------------------------------------+
| ID | USER | HOST | DB | COMMAND | TIME | STATE | QUERY |
+---------+--------+------------+-------------------+---------+------+----------+------------------------------------------------------------------------------------------------------------------------------+
| 2786271 | appy | borg:89700 | global_app_center | Query | 12 | updating | SELECT `posts` FROM `blog` WHERE `authors`.`id` IN ( 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2.. | |
+---------+--------+------------+-------------------+---------+------+----------+------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
set @width=160; select ID, USER, HOST, DB, COMMAND, TIME, STATE, concat(substr(INFO,1,@width),IF(LENGTH(INFO) > @width, ' ...', '')) as QUERY from INFORMATION_SCHEMA.PROCESSLIST where time > 5 and COMMAND <> 'Sleep';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment