Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop a MySQL query if it takes too long?

Tags:

mysql

timeout

Is it possible to timeout a query in MySQL?

That is, if any query exceeds the time I specify, it will be killed by MySQL and it will return an error instead of waiting for eternity.

like image 893
acheruns Avatar asked Jan 26 '10 01:01

acheruns


People also ask

How do I stop a long running query in MySQL?

Run the following command: mysql> SELECT GROUP_CONCAT(CONCAT('KILL ',id,';') SEPARATOR ' ') FROM information_schema. processlist WHERE user <> 'system user'; This will kill all your MySQL queries.

Why is MySQL query taking so long?

There are a number of things that may cause a query to take longer time to execute: Inefficient query – Use non-indexed columns while lookup or joining, thus MySQL takes longer time to match the condition. Table lock – The table is locked, by global lock or explicit table lock when the query is trying to access it.

How do I exit a MySQL query?

If a command is not terminated by a semi-colon, pressing enter simply continues the current command on the following line. To exit from mysql type quit at the mysql> command-prompt.


1 Answers

There is a nice Perl script on CPAN to do just this: http://search.cpan.org/~rsoliv/mysql-genocide-0.03/mysql-genocide

One only needs to schedule it to run with the proper parameters. Create a CRONtab file /etc/cron.d/mysql_query_timeout to schedule it to run every minute:

* * * * * root /path/to/mysql-genocide -t 7200 -s -K

Where 7200 is the maxiumum allowed execution time in seconds. The -s switch filters out all except SELECT queries. The -K switch instructs the script to kill the matching processes.

The root user should be able to run local mysql tools without authentication otherwise you will need to provide credentials on the command line.

like image 137
Erik Avatar answered Sep 24 '22 16:09

Erik