Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - can I limit the maximum time allowed for a query to run?

I'm looking for a way to limit the max running time of a query on mysql server. I figured this could be done through the my.cnf configuration file, but couldn't find anything relevant in the docs. Anyone knows if this could be done? thanks.

like image 666
sa125 Avatar asked Jan 25 '11 14:01

sa125


People also ask

How do I set query timeout in MySQL?

Or you can set a session-wide or global timeout: SET SESSION MAX_EXECUTION_TIME=2000; SET GLOBAL MAX_EXECUTION_TIME=2000; The timeouts only apply to read-only SELECT queries. You can handle this error centrally in your application and display message to users that the response took too long and was aborted.

Is there a limit clause in MySQL?

The MySQL LIMIT ClauseThe LIMIT clause is used to specify the number of records to return. The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.


1 Answers

Update

As of MySQL 5.7, you can include a MAX_EXECUTION_TIME optimizer hint in your SELECT queries to instruct the server to terminate it after the specified time.

As far as I know, if you want to enforce a server-wide timeout, or if you care about queries besides SELECTs, the original answer is still your only option.

Original answer

There is no way to specify a maximum run time when sending a query to the server to run.

However, it is not uncommon to have a cron job that runs every second on your database server, connecting and doing something like this:

  1. SHOW PROCESSLIST
  2. Find all connections with a query time larger than your maximum desired time
  3. Run KILL [process id] for each of those processes
like image 130
TehShrike Avatar answered Oct 03 '22 20:10

TehShrike