Finding and killing long running MySQL queries

Sometimes (Woocommerce?) related queries on a MySQL server can seemingly run forever and eventually lead to the server being clogged up (and few free connections).

Something like this can help …. (i.e. kill all MySQL queries which have been running longer than 900 seconds, and aren’t from the ‘root’ user).



# assume e.g. ~/.my.cnf exists with user/password etc.

QUERY="SELECT id FROM information_schema.processlist
     WHERE command <> 'Sleep' 
     AND command <> 'Killed' 
     AND user != 'root' AND time > 900"

for PID in $(mysql -u root -BNe $QUERY )
    # Log it ... 
    LOG_QUERY="SELECT * FROM information_schema.processlist WHERE id = $PID \G"

    OUTPUT=$(mysql -u root -NBe $LOG_QUERY)
    echo "Long running query : $OUTPUT "
    # If on AWS RDS then : mysql -u root -e "call mysql.rds_kill($PID)"
    # otherwise, in a normal environment :
    mysql -u root -e "KILL $PID"


Leave a Reply

Your email address will not be published. Required fields are marked *