Skip to content
Advertisement

Oracle SQL merge tables side by side

I have 3 select queries which i would like to merge side by side. The common column is name. I dont want to use UNION ALL solutions since my select queries might have many columns.

(select 'e1' name,1 columna  from dual) table_1
name  columna  
e1    1  
(select 'h1' name,2 columnb  from dual) table_2
name    columnb    
h1      2  
(select 't1' name,3 columnc  from dual) table_3
name    columnc
t1      3  

The output i am looking for is:

name columna columnb columnc  
e1   1     
h1           2
t1                   3

I believe I need the full outer join. I tried left outer with (+) syntax.

select table_1.name,columna,columnb,columnc from  
(select 'e1' name,1 columna  from dual) table_1,  
(select 'h1' name,2 columnb  from dual) table_2,  
(select 't1' name,3 columnc  from dual) table_3  
where  
table_1.name=table_2.name(+)  
and table_1.name=table_3.name(+)  

but the output is:

name columna columnb columnc
e1   1     

Advertisement

Answer

Perhaps you’re after something like the following?:

with t1 as (select 'e1' name, 1 columna from dual),
     t2 as (select 'h1' name, 2 columnb, 2.5 columnc from dual),  
     t3 as (select 't1' name, 3 columnd from dual union all
            select 'h1' name, 4 columnd from dual)
select coalesce(t1.name, t2.name, t3.name) name,
       t1.columna,
       t2.columnb,
       t2.columnc,
       t3.columnd
from   t1
       full outer join t2 on t1.name = t2.name
       full outer join t3 on t1.name = t3.name or t2.name = t3.name
order by name;

NAME    COLUMNA    COLUMNB    COLUMNC    COLUMND
---- ---------- ---------- ---------- ----------
e1            1                       
h1                       2        2.5          4
t1                                             3

This uses full outer joins to join the tables together (note the use of the “OR” when joining the third table), and assumes the name column is unique in each table.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement