brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: max_statement_time stops a runaway database query after a set number of seconds

Database
~/tips/tip-database-mariadb-max-statement-time

SET STATEMENT max_statement_time = 5 FOR

Sets a time limit so a slow query is aborted instead of running for hours.

A report query without a good index can run for an hour and hold the server busy the whole time. MariaDB can kill such queries for you once they pass a limit.

SET SESSION max_statement_time = 5;
SET STATEMENT max_statement_time = 5 FOR
  SELECT customer, SUM(total) FROM orders GROUP BY customer;

The value is in seconds, and fractions work too. The first line applies to every later query in that connection. The second form wraps a single statement, which I like for one heavy report without changing the rest of the session. A query that runs too long stops with:

ERROR 1969 (70100): Query execution was interrupted (max_statement_time exceeded)

You can also set it per user, for example for a read-only reporting account, with ALTER USER report WITH MAX_STATEMENT_TIME 30; so nobody has to remember it. The default is 0, which means no limit.

A word of warning about where you set it. As a global value it also hits mariadb-dump, ALTER TABLE and other long jobs you do want to finish, so I prefer it per session or per user. The server checks the timer at intervals, so a query can run a little past the limit before it stops. And MySQL has a similar setting with a different name and unit, max_execution_time in milliseconds, which only works for SELECT.

Further reading: Aborting statements that take longer than a certain time

More Database tips mariadb -e 'CREATE DATABASE IF NOT EXISTS blog' mariadb-dump --no-create-info --insert-ignore shop orders > orders-rows.sql SELECT table_schema, table_name, CHECKSUM TABLE shop.orders; services: All Database tips (53) All topics

Link