Many SQL databases support what the SQL standard calls a <derived column list>
. Such databases include at least CUBRID, Derby, Firebird, HSQLDB, Postgres, SQL Server, and Sybase SQL Anywhere. A (simplified) extract from the SQL:2008 specification
7.6 <table reference>
Format
<table reference> ::=
<table or query name> [ [ AS ] <correlation name>
[ <left paren> <derived column list> <right paren> ] ]
| <derived table> [ AS ] <correlation name>
[ <left paren> <derived column list> <right paren> ]
This means, I can express things like these (e.g. in Postgres, which is pretty standards-compliant)
-- Rename a <table or query name> to u(b)
with t(a) as (select 1)
select * from t as u(b)
-- Rename a <derived table> to u(b)
select * from (select 1) as u(b)
Now, according to the Oracle documentation, I can't rename columns using a <derived column list>
specification. I could of course rename tables and columns separately, like this:
-- Rename a <table or query name> to u(b)
with t(a) as (select 1 from dual)
select u.a b from t u;
-- Rename a <derived table> to u(b)
select u.a b from (select 1 a from dual) u;
But this requires more knowledge about the derived table (actual column names) than the previous syntax. Also, the renamed columns would only be available after the projection (e.g. in the ORDER BY
clause), not in any other clauses, including the projection itself.
Is there a more generic way to rename tables AND columns the way the SQL standard suggests, in Oracle (and also MySQL)? In particular, this could be useful for things like array unnesting, pivot/unpivot table renaming, inlining complex subqueries, renaming results from table functions, etc.
N.B: Please do not focus on the above examples too much. They're really just here to illustrate the problem. Real-world queries are much more complex, so I'm looking for a very general way to implement renaming to u(b)
NOTE: I'm still looking for a solution that works on a database like MySQL. A related question:
How to select an unaliased numeric literal from a sub-select