Search code examples
mysqlsqlselectorder-of-execution

Execution order of expressions in SELECT statement


I want to know if the execution order of expressions in SELECT statement always takes place from left to right.

SET @a := 0;

SELECT 
@a AS first,
@a := @a + 1 AS second,
@a := @a + 1 AS third,
@a := @a + 1 AS fourth,
@a := @a + 1 AS fifth,
@a := @a + 1 AS sixth;

Is it guaranteed that the above query will always generate the following output?

first second third fourth fifth sixth 
  0     1      2     3     4      5

Solution

  • According to the MySQL manual:

    However, the order of evaluation for expressions involving user variables is undefined

    So the answer to your question, is no, the execution order is not guaranteed.