12

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?

2 Answers 2

15

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

1
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
2
  • 1
    doesn't it make two function calls to get the same value?
    – Jenn
    Jul 1, 2010 at 11:08
  • @Jenn If the function is deterministic, it will be called just once.
    – Cade Roux
    Jul 1, 2010 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.