How to Abort SQL Statements After a Set Time in MariaDB

Sometimes you don’t want a SELECT query to run for more than a set amount of time.

This is a roundabout way to make your server doesn’t die from slow-running queries.

Obviously, you should tweak your database and potentially run your SELECT queries through an EXPLAIN plan first. This allows you to create appropriate indexes and find why things are slow in the first place.

But: sometimes you still find yourself wanting to kill queries that may run over a certain amount of time.

How to abort slow queries

Your original query:

SELECT b.domain as domain ...

Your new query:

SET STATEMENT max_statement_time=30 FOR SELECT b.domain as domain ...

Notice the addition of the SET STATEMENT max_statement_time=30 right before the SELECT.

This is measured in seconds, so the above query will automatically be killed after 30 seconds.