SET STATEMENT
SET STATEMENT can be used to set the value of a system variable for the duration of the statement. It is also possible to set multiple variables.
Syntax
SET STATEMENT var1=value1 [, var2=value2, ...]
FOR <statement>var is a system variable (list of allowed variables is provided below), and value is a constant literal.
Description
SET STATEMENT var1=value1 FOR stmt
is roughly equivalent to
SET @save_value=@@var1;
SET SESSION var1=value1;
stmt;
SET SESSION var1=@save_value;The server parses the whole statement before executing it, so any variables set in this fashion that affect the parser may not have the expected effect. Examples include the charset variables, sql_mode=ansi_quotes, etc.
Examples
One can limit statement execution time max_statement_time:
SET STATEMENT max_statement_time=1000 FOR SELECT ... ;One can switch on/off individual optimizations:
SET STATEMENT optimizer_switch='materialization=off' FOR SELECT ....;It is possible to enable MRR/BKA for a query:
SET STATEMENT join_cache_level=6, optimizer_switch='mrr=on' FOR SELECT ...Note that it makes no sense to try to set a session variable inside a SET STATEMENT:
#USELESS STATEMENT
SET STATEMENT sort_buffer_size = 100000 FOR SET SESSION sort_buffer_size = 200000;For the above, after setting sort_buffer_size to 200000 it will be reset to its original state (the state before the SET STATEMENT started) after the statement execution.
Limitations
There are a number of variables that cannot be set on per-query basis. These include:
autocommitcharacter_set_clientcharacter_set_connectioncharacter_set_filesystemcollation_connectiondefault_master_connectiondebug_syncinteractive_timeoutgtid_domain_idlast_insert_idlog_slow_filterlog_slow_rate_limitlog_slow_verbositylong_query_timemin_examined_row_limitprofilingprofiling_history_sizequery_cache_typerand_seed1rand_seed2skip_replicationslow_query_logsql_log_offtx_isolationwait_timeout
Source
The feature was originally implemented as a Google Summer of Code 2009 project by Joseph Lukas.
Percona Server 5.6 included it as Per-query variable statement
MariaDB ported the patch and fixed many bugs. The task in MariaDB Jira is MDEV-5231.
This page is licensed: CC BY-SA / Gnu FDL
Last updated
Was this helpful?

