Occasionally, you find yourself in the need to kill problematic
connections to the database.
Usually if it's only one or two connections, you can use the
combination of "SHOW PROCESSLIST" command to identify the
problematic connection ID, and run a "KILL ID" command.
What do you do if you need to kill 10 connections? Or 56? I wouldn't want to type in all those kill commands, it's just dirty work. What we need is a more neat manner to perform those kills. Mass kill, if you wish.
Alternative way: use the INFORMATION_SCHEMA's PROCESSLIST table, to construct the kill statements semi-automatically.
SELECT CONCAT('kill ',id,';') AS kill_list
FROM INFORMATION_SCHEMA.PROCESSLIST
WHERE command='Sleep';
This select will return something like this (when using the
command line client):
+-----------+
| kill_list |
+-----------+
| kill 28; |
| kill 1; |
+-----------+
2 rows in set (0.04 sec)
You can also use GROUP_CONCAT() to get the kill commands in the same line, which may be more useful when you can't copy&paste easily:
SELECT GROUP_CONCAT('kill ',id SEPARATOR '; ') AS
kill_list
FROM INFORMATION_SCHEMA.PROCESSLIST
WHERE command='Sleep';
Returns:
+------------------+
| kill_list |
+------------------+
| kill 28;,kill 1; |
+------------------+
1 row in set (0.03 sec)
Note, that you can use any filter in the WHERE clause, such as "WHERE db IN('dbname1','dbname2')", "WHERE user = 'appuser'" or "WHERE time>600". If you got any more clever uses, feel free to post them in the comments.
Now, all needed is to copy&paste those kill commands into the mysql command console (whichever you're using: GUI, command line, etc) and you're done.
Since most programs are kind enough to format the output in some way that prevents convenient copying/pasting, here's another tip. The mysql command line client can be asked to strip some of the output by using the "-s" optional parameter, which stands for "silent". You can use it once, and remove the ASCII art, timing and row count, and if you use it again (-s -s), you only get the actual rows.
An example doing just this (copy&paste friendly!):
mysql -s -s -e "SELECT CONCAT('kill ',id,';') AS kill_list
FROM INFORMATION_SCHEMA.PROCESSLIST WHERE
command='Sleep';"
Gets you this (with different numbers of course):
kill 28;
kill 1;
Another way to do this, is to use SQLyog or any other GUI for MySQL, which can output the results in text. Most of them have this as a configurable option (Ctrl-L keyboard shortcut in SQLyog).
Hope this is will save someone some precious time.
Update:
I didn't include a suggestion on doing this automatically, since
I personally prefer to run kill commands manually most of the
time. Plus, some of the comments gave me an idea. Why not just
pipe the stripped kill_list into mysql?
mysql -s -s -e "SELECT
GROUP_CONCAT('kill ',id
SEPARATOR '; ')
AS kill_list FROM
INFORMATION_SCHEMA.PROCESSLIST WHERE command='Sleep';" |
mysql