Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I use an alias in a SELECT clause, how do I refer back to that alias?

Tags:

sql

I want to do something like this:

SELECT round(100*(col_a - col_b)/col_a, 1) as Foo, Foo - col_c as Bar
FROM my_table
WHERE...;

However, I get an error saying Foo is unknown. Since Foo is derived from some calculations on a bunch of other columns, I don't want to repeat the formula again for Bar. Any work-arounds?

like image 356
code_martial Avatar asked Aug 19 '11 10:08

code_martial


People also ask

Can you reference an alias in SQL?

You can't reference an alias except in ORDER BY because SELECT is the second last clause that's evaluated.

Can you reference alias in WHERE clause?

column_alias can be used in an ORDER BY clause, but it cannot be used in a WHERE, GROUP BY, or HAVING clause. Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined.

Can you alias a SELECT statement?

Alias is used to give a temporary name(only for the duration of the query) to the column or table in order to make the column name or table name more readable. It does not change the name of the column permanently.

Can alias Use same SELECT statement?

In MySQL you CAN reference a select column alias in the same select, as long as it precedes the reference point.


1 Answers

SELECT Foo, Foo - col_c as Bar
from (
SELECT round(100*(col_a - col_b)/col_a, 1) as Foo,  col_c
FROM my_table
WHERE...

) t;
like image 94
triclosan Avatar answered Nov 15 '22 19:11

triclosan