Open lukaseder opened 3 years ago
The resolution of these "lateral column references" requires much more thought:
SELECT x AS a, a FROM t
where t
has a column a
)SELECT x AS a, (SELECT a FROM t) FROM t
where t
has a column a
)A much more simple, related feature has been implemented:
This seems to be a popular request for users who translate SQL away from Teradata et al. I'll reconsider this for jOOQ 3.18. With the current infrastructure, it seems not too hard to implement.
DuckDB seems to have implemented something similar.
Teradata bends the rules of the logical order of SQL operations quite a bit, see: https://blog.jooq.org/a-beginners-guide-to-the-true-order-of-sql-operations/
In Teradata, it seems that these are possible:
Referencing column alias from
WHERE
:This would need to be transformed to either:
Both approaches can lead to funny edge cases.
Note that it is also possible to do this kind of thing in PostgreSQL and possibly others, when referencing columns from
GROUP BY
orHAVING
by index or name.Referencing column alias from
SELECT
:It seems that a left-to-right name resolution is happening, allowing for aliases to be used on the same level of their declaration. Why not? Again, this can be transformed to either:
Reverse engineered rules:
SELECT
expressions can be referenced from:WHERE
GROUP BY
HAVING
QUALIFY
SELECT
(irrespective of order, as long as there are no cycles)FROM
The interesting bit is that there seems to be some sort of cycle detection when referencing aliases in
SELECT
:The last query fails with:
Subqueries:
This works and produces:
However,
b
is not in scope for further references, e.g. this doesn't work:Producing:
Despite the projected name being
b
!Conflict resolution:
Ambiguous top level projected columns
This works, and produces
So, in such an ambiguous case, only the last definition of
a
is being consideredRe-declaration of existing column
This works as in all other dialects, and produces the standard result:
So, while the projected alias is available to
ORDER BY
like everywhere else, it does not affect same level projection references (or references fromWHERE
, etc.) if there's already a column by the same name in scope.Implementation tasks
Transformation
flag is offered, includingNEVER
,WHEN_NEEDED
, andALWAYS
FROM
clause. E.g. when using the parser, meta data must be available on all tables, for the transformation to work. Otherwise, it will be safer to assume a column reference is from theFROM
clause, not theSELECT
clause.SELECT
clause, but not from theFROM
clause, shall be substituted, if it is substitutable:Dialect support: