Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using alias in query and using it

Tags:

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 ?

like image 990
asb Avatar asked Jan 13 '10 07:01

asb


People also ask

Can I use alias in same query?

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

How alias use in SQL query?

SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to make column names more readable. An alias only exists for the duration of that query. An alias is created with the AS keyword.

Why aliases are used in writing of query?

The SQL alias assigns a placeholder name to a table or a column in a table. Aliases are useful because they help make queries and their results more readable and easier to interpret. A good alias is one that can be understood as quickly as possible.

Can we use alias in subquery?

SQL Correlated Subqueries are used to select data from a table referenced in the outer query. The subquery is known as a correlated because the subquery is related to the outer query. In this type of queries, a table alias (also called a correlation name) must be used to specify which table reference is to be used.


1 Answers

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.

like image 81
Josh Avatar answered Sep 29 '22 22:09

Josh