Jenn
Jenn

Reputation: 129

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?

Upvotes: 12

Views: 13866

Answers (2)

MJB
MJB

Reputation: 7686

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

Upvotes: 1

mdma
mdma

Reputation: 57777

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.)

Upvotes: 15

Related Questions