Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the sql execution time

Tags:

sql

mysql

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?

like image 200
worldterminator Avatar asked Aug 02 '12 07:08

worldterminator


People also ask

How do you set limits in SQL?

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.

How do I change the execution time in MySQL?

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.

How long should a SQL query take to execute?

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.


2 Answers

To auto kill a query in MySQL after a long execution time:

  1. 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;
    
  2. 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.

like image 84
Omesh Avatar answered Oct 05 '22 20:10

Omesh


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.

like image 39
Radu Maris Avatar answered Oct 05 '22 20:10

Radu Maris