Some sql is not well written. Sometimes a search costs hours in applications. When a application(maybe a website) submit a query which run long time, I have to restart the mysql. How can I limit a sql query's execution time in the database side?
The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.
SET SESSION MAX_EXECUTION_TIME=2000; Then any SELECT statements run in this particular session are aborted if they take more than 2 seconds to complete. Finally, the maximum execution time can also be set for a specific SELECT statement using the MAX_EXECUTION_TIME hint directly in the query.
The query takes 20 to 500 ms (or sometimes more) depending on the system and the amount of data. The performance of the database or the database server has a significant influence on the speed.
To auto kill a query in MySQL after a long execution time:
Create a stored procedure as:
DECLARE CURSOR cur1 FOR SELECT ID
FROM INFORMATION_SCHEMA.PROCESSLIST
WHERE COMMAND = 'Query' AND TIME > 120;
then inside curosr's loop do:
FETCH ID INTO @var_kill_id;
KILL QUERY @var_kill_id;
Create EVENT FOR EVERY 5 SECONDS
and just CALL
the above procedure inside it.
Note: KILL QUERY just kills the query and MySQL connection is not broken. see here.
Also if possible you can try Twitter's mysql fork that suport "max_statement_time" and kills a query exceding it, at a milisecond granularity.
See http://engineering.twitter.com/2012/04/mysql-at-twitter.html and https://github.com/twitter/mysql/wiki/Statement-Timeout
Original source.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With