Giovane Giovane - 7 months ago 10
SQL Question

Union with different number of columns

I have three columns in the first table, the second table have one column that exists in the first table and 2 I want to add.

Ex:

select c1 as col1, c2 as col2, c3 as col3
from Table1
union
select c1, c4 as col4, c5 as col5
from Table2

expected Result:

col1,col2,col3,col4,col5

Answer

Just add null or any other default value you like as static column

select  c1 as col1, 
        c2 as col2, 
        c3 as col3, 
        null as col4, 
        null as col5
from    Table1
union
select  c1, 
        null, 
        null, 
        c4,
        c5
from    Table2