How to forbid using the same table alias twice in a query?

Viewed 103

I am running Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production Version 19.8.0.0.0.

Consider the following example:

create table tab_a as
          select 1 as id from dual
union all select 2 as id from dual
union all select 3 as id from dual
;

create table tab_b as
          select 1 as id, 'b1' as val, 'bbb1' as val_b from dual
union all select 2 as id, 'b2' as val, 'bbb2' as val_b from dual
;

create table tab_c as
          select 1 as id, 'c1' as val, 'ccc1' as val_c from dual
union all select 3 as id, 'c3' as val, 'ccc1' as val_c from dual
;

select
  a.id
 ,b.val
 ,b.val_b
 ,b.val_c
from
  tab_a a
  left join tab_b b on b.id = a.id
  left join tab_c b on b.id = a.id
order by
  a.id
;

As you can see, I reused the "b" alias on another table (duplicate). This is the result:

        ID VAL        VAL_2      VAL_3
---------- ---------- ---------- ----------
         1 b1         bbb1       ccc1
         2 b2         bbb2       (null)
         3 (null)     (null)     ccc1

So:

  • the column "val", present in both tables, is taken from tab_b, which was declared first
  • the column "val_b" is taken from tab_b
  • the column "val_c" is taken from tab_c

It appears that Oracle assigns the alias to both tables with a priority and it does not report it as incorrect syntax. But this is something I would like to avoid. I was surprised to have discovered this Bug in my query. Is this behavior known? Can anything be done to enforce unique aliases?

0 Answers
Related