Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a variable within select and use it within the same select

Is there a possibility to do something like this?

SELECT      @z:=SUM(item),     2*@z FROM     TableA; 

I always get NULL for the second column. The strange thing is, that while doing something like

SELECT      @z:=someProcedure(item),     2*@z FROM     TableA; 

everything works as expected. Why?

like image 449
user2370579 Avatar asked May 23 '13 13:05

user2370579


People also ask

How do you DECLARE a variable in a SELECT statement?

SELECT @local_variable is typically used to return a single value into the variable. However, when expression is the name of a column, it can return multiple values. If the SELECT statement returns more than one value, the variable is assigned the last value that is returned.

How do you SET a variable in a SELECT statement in SQL Server?

To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

How do you SELECT the value of a variable in MySQL?

There are two ways to assign a value to a user-defined variable. You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter. The second way to assign a value to a variable is to use the SELECT statement.


2 Answers

MySQL documentation is quite clear on this:

As a general rule, you should never assign a value to a user variable and read the value within the same statement. You might get the results you expect, but this is not guaranteed. The order of evaluation for expressions involving user variables is undefined and may change based on the elements contained within a given statement; in addition, this order is not guaranteed to be the same between releases of the MySQL Server. In SELECT @a, @a:=@a+1, ..., you might think that MySQL will evaluate @a first and then do an assignment second. However, changing the statement (for example, by adding a GROUP BY, HAVING, or ORDER BY clause) may cause MySQL to select an execution plan with a different order of evaluation.

You can do what you want using a subquery:

select @z, @z*2 from (SELECT @z:=sum(item)       FROM TableA      ) t; 
like image 119
Gordon Linoff Avatar answered Sep 24 '22 07:09

Gordon Linoff


Works in mysql 5.5

select @code:=sum(2), 2*@code  +---------------+---------+ | @code:=sum(2) | 2*@code | +---------------+---------+ |             2 |       4 | +---------------+---------+ 
like image 22
Ravi Parekh Avatar answered Sep 24 '22 07:09

Ravi Parekh