Skip to content
Advertisement

Using alias in query and using it

I have a doubt and question regarding alias in sql. If i want to use the alias in same query can i use it. For eg: Consider Table name xyz with column a and b

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

Is this possible in some way ?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement