Search code examples
sqlunionvertica

Union all in Vertica SQL based on tables with different number of columns?


Hellow i have two tables in Vertica SQL:

table 1

col1  col2  col3
1      3    5
2      4    6

table 2

col1  col2
11    33
22    44

And I would like to UNION these two tables, so as as result I would like to have:

col1  col2  col3
1      3     5
2      4     6
11     33    NULL
22     44    NULL

How can I do it in vertica


Solution

  • In general, you should use UNION ALL and define the extra column with whatever default value you want:

    select col1, col2, col3
    from table1
    union all
    select col1, col2, NULL as col3
    from table2;
    

    UNION incurs overhead for removing duplicates. In general, you should use UNION ALL unless you intend to remove duplicates.