Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build "dummy columns" for UNION?

Tags:

sql

from what I understand "each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order." Well what if the first SELECT has more columns than the 2nd one can generate. Here's what I mean: let's say I want to

SELECT "City", "Country", "Continent" from table1  
UNION  
SELECT "City", "Country" from table2     

...let's say table 2 does not contain a column called "Continent" but for my needs it's fine for the records that come from table2 to have a blank or NULL in that column. I am using dashDB.

like image 958
Mike Pala Avatar asked Sep 29 '16 09:09

Mike Pala


People also ask

How do you union null values in SQL?

The SQL UNION operator treats all NULL values as a single NULL value when evaluating duplicate. When combining with UNION, the ALL or DISTINCT operator is optional. The ALL operator allows duplicate rows to appear in the combined result set. The DISTINCT operator eliminates duplicate rows.


Video Answer


2 Answers

You can always add "virtual" columns:

SELECT "City", "Country", "Continent" from table1  
UNION  
SELECT "City", "Country", NULL AS "Continent" from table2 
like image 64
Tim Schmelter Avatar answered Oct 19 '22 11:10

Tim Schmelter



Hi,
You can use,

 SELECT "City", "Country", "Continent" from table1  
UNION  
SELECT "City", "Country", ' ' as "Continent"  from table2

or

 SELECT "City", "Country", "Continent" from table1  
    UNION  
    SELECT 

"City", "Country", NULL as "Continent"  from table2

It considers "Continent" as null in table2

like image 36
Jim Macaulay Avatar answered Oct 19 '22 13:10

Jim Macaulay