Using UNION, multiple SELECT statements can be specified, and their results can be combined into a single result set.
A UNION must be comprised of two or more SELECT statements, each separated by the keyword UNION.
Each query in a UNION must contain the same columns, expressions or aggregate functions Column data types must be compatible
The column names in the result-set are usually equal to the column names in the first SELECT statement in the UNION.
SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; |
The UNION automatically removes any duplicate rows from the query result set.
If you want all occurrences of all matches returned, then you can use UNION ALL.
SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2; |
Let's look at the "Orders" table data below:
Orderid | Customernumber | Orderdate | City |
---|---|---|---|
1001 | 10 | 2020-09-08 | London |
1002 | 99 | 2020-09-01 | Newyork |
1003 | 17 | 2020-08-25 | Paris |
1004 | 76 | 2020-09-19 | Dubai |
1005 | 44 | 2020-09-25 | Sydney |
Let's look at the "Customers" table data below:
Customernumber | Customername | Country | City |
---|---|---|---|
76 | Jack | America | Newyork |
17 | Jancy | Germany | California |
20 | Carmen | Russia | London |
10 | Robert | India | Newdelhi |
99 | Brian | China | Chennai |
The following SQL statement returns the cities (only distinct values) from both the "Orders" and the "Customers" table.
SELECT City FROM Orders UNION ALL SELECT City FROM Customers ORDER BY City; |
If "Orders" or "Customers" have the same city, each city will only be listed once, because UNION selects only distinct values. Use UNION ALL to include duplicate values.
City |
---|
California |
Chennai |
Dubai |
London |
Newdelhi |
Newyork |
Paris |
Sydney |
If you want all occurrences of all matches returned, then you can use UNION ALL instead of UNION.
The following SQL statement returns the cities (with duplicates) from both the "Orders" and the "Customers" table.
SELECT City FROM Orders UNION SELECT City FROM Customers ORDER BY City; |
If "Orders" or "Customers" have the same city, each city will only be listed once, because UNION selects only distinct values. Use UNION ALL to also select duplicate values
City |
---|
California |
Chennai |
Dubai |
London |
London |
Newdelhi |
Newyork |
Newyork |
Paris |
Sydney |
If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!