Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a function result as my alias?

Tags:

sql

I am wondering if it is possible to use an SQL function to name the column of a query. As a simple example:

SELECT id AS SUBSTR('xAlias', 2) FROM foo

should theoretically return

Alias
------
...
results
...

If we can, which databases would this be available for? If not, then why?

like image 474
Roman Avatar asked Feb 13 '12 19:02

Roman


People also ask

What is function alias?

Function aliases of this type provide natural-language descriptions and prompting for input parameters to an underlying function rule. You need to create and test the function before defining a function alias rule that references it. You cannot define an alias for a function that returns a complex Java type.

How do you specify an alias in SQL?

The basic syntax of a table alias is as follows. SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition];

Can you reference an alias in SQL?

5 Answers. Show activity on this post. You can't reference an alias except in ORDER BY because SELECT is the second last clause that's evaluated.


2 Answers

AFAIK, there is no SQL way in any major DBMS product to support this.

To name PIVOT columns in Oracle, for name in.. as seems like the best option.
Apart from that, it's over to dynamic SQL.


Original answer below

To name the column of a query, the ANSI standard is simply to add the new name after the column (derived or base) prepended by "AS":

SELECT id, field1, field2 * qty FROM foo

All columns renamed below:

SELECT id AS RenamedID, field1 AS Col1, field2 * qty AS ExtendedTotal FROM foo

This standard works for pretty much all major database systems.
There are some vendor specific variations, such as SQL Server allowing the equal sign

SELECT RenamedID=id FROM foo

And most DBMS allow the omission of the "AS" keyword

SELECT id RenamedID FROM foo
like image 180
RichardTheKiwi Avatar answered Oct 02 '22 19:10

RichardTheKiwi


That's a weird requirement and I think no DBMS would support that. I did the test anyway and here are the results:

This doesn't work in SQL Server 2008, MySQL 5 nor PostgreSQL 9 (they share the same sintax):

SELECT id AS left('xAlias', 2) FROM table

In Oracle 11g and SQLite 3 this failed too:

SELECT id AS substr('xAlias', 1, 2) FROM table

I bet you won't find any that supports that :P

like image 27
Mosty Mostacho Avatar answered Oct 02 '22 17:10

Mosty Mostacho