Using Column Alias in Same SELECT Clause

No there isn’t a way to refer to aliases, but you can assign the expression to a variable, and then refer to the variable in the same select clause.

Inside a select statement variable assignment is always done by the infix operator :=. *In a SET statement, it can be either = or :=.

e.g.

SELECT 
    ord_id
  , candy_id
  , price
  , quantity
  , @exc_cost := price * quantity AS exc_cost
  , @exc_cost * @tax_rate AS my_favourite_field
...
<FROM CLAUSE>

You can also conditionally perform variable assignment.

e.g.

IF(quantity > 90, 
     @exc_cost := price * quantity * 0.95
   , @exc_cost := price * quantity) AS exc_cost

Note 1: In the absence of aggregate measures & group by clause, the variables are evaluated according to column order:

SELECT @t, @t+2 FROM (SELECT @t := 1) a

produces the output

@t   @t+2
 1      3

Leave a Comment

techhipbettruvabetnorabahisbahis forumu