Comments - User-Defined Variables

6 years, 10 months ago Verizon Team DB

The text of this article says

"It is unsafe to read a user-defined variable and set its value in the same statement (unless the command is SET), because the order of these actions is undefined."

One of the examples does precisely that:

SELECT a, b, c, (@var:=@var+1) AS counter FROM my_table;

Is the example somehow safe?

 
4 years, 8 months ago Dean Trower

Check the docs for MySQL for more detail. The "order" of @var:=@var+1 is never undefined, as the RHS *must* be evaluated first. The problem is that the order of evaluation of *columns* is undefined, so:

SET @v := 5; SELECT @v, @v:=10;

Might return either [5,10] or [10,10], depending on which column is evaluated first.

 
11 months, 3 weeks ago Fabio Valeri

"Evaluation of *columns* is undefined". That is that SELECT @v:=5, @v=@v+5 may return [5,10] or [10,5] because the order of columns in SELECT col1, col2 does not follow from left to right? I assume that this is because of sql-philosophy (set theory) since order does not play a role. Is there a way to consider the order?

 
Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.