Using alias in query and using it

Not possible in the same SELECT clause, assuming your SQL product is compliant with entry level Standard SQL-92.

Expressions (and their correlation names) in the SELECT clause come into existence 'all at once'; there is no left-to-right evaluation that you seem to hope for.

As per @Josh Einstein's answer here, you can use a derived table as a workaround (hopefully using a mote meaningful name than 'temp' and providing one for the temp/5 expression -- have in mind the person who will inherit your code).

Note that code you posted would work on the MS Access Database Engine (and would assign a meaningless correlation name such as Expr1 to your second expression) but then again it is not a real SQL product.


You can use Oracle with statement too. There are similar statements available in other DBs too. Here is the one we use for Oracle.

with t
as (select a/b as temp
from xyz)
select temp, temp/5
from t
/

This has a performance advantage, particularly if you have a complex queries involving several nested queries, because the WITH statement is evaluated only once and used in subsequent statements.


You are talking about giving an identifier to an expression in a query and then reusing that identifier in other parts of the query?

That is not possible in Microsoft SQL Server which nearly all of my SQL experience is limited to. But you can however do the following.

SELECT temp, temp / 5
FROM (
    SELECT (a/b) AS temp
    FROM xyz
) AS T1

Obviously that example isn't particularly useful, but if you were using the expression in several places it may be more useful. It can come in handy when the expressions are long and you want to group on them too because the GROUP BY clause requires you to re-state the expression.

In MSSQL you also have the option of creating computed columns which are specified in the table schema and not in the query.

Tags:

Sql

Alias