Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we give multiple alias for a column in SQL?

I have a function call in a query, and that result has to be returned with two names.

Example:

SELECT myFunction(column1) as Name1, column2 as Name2 FROM myTable

I want the result of myFunction to be returned in two different columns. Is this possible without making another function call in the column list?

like image 209
Jenn Avatar asked Jul 01 '10 11:07

Jenn


People also ask

How can I give two alias names in SQL?

You can't give a name two aliases directly, but you can repeat a column in a derived query: SELECT name1, name1 AS name2 FROM (SELECT myFunction(column1) As Name1 From MyTable) base; You might also simply duplicate the function call.

How do I give an alias to multiple columns in SQL?

Yes, you can alias multiple columns at a time in the same query. It is advisable to always include quotes around the new alias. Quotes are required when the alias contains spaces, punctuation marks, special characters or reserved keywords. It is simply more convenient to always include quotes around the new alias.

Can we add alias columns 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.

How can I alias column name in SQL Server?

SQL Server column alias To assign a column or an expression a temporary name during the query execution, you use a column alias. In this syntax, you use the AS keyword to separate the column name or expression and the alias.


2 Answers

You can't give a name two aliases directly, but you can repeat a column in a derived query:

SELECT name1, name1 AS name2 FROM 
  (SELECT myFunction(column1) As Name1 From MyTable) base;

You might also simply duplicate the function call. If the function is deterministic then the optimizer may call it just once. (But of course, check the query plan.)

like image 104
mdma Avatar answered Sep 18 '22 15:09

mdma


SELECT myFunction(column1) as Name1, myFunction(column1) as Name2 FROM myTable

I am guessing this is what you mean. This is often used in a framework that expects a return value and a display value for a drop down list. For example,

select name as DisplayVal, name as ReturnVal from Table
like image 37
MJB Avatar answered Sep 16 '22 15:09

MJB