IBM Support

Difference between UNION and UNION ALL in DB2

Question & Answer


Question

What is the difference between UNION and UNION ALL in DB2?

Answer

When DB2 encounters the UNION keyword, it processes each select / subselect to form an interim result table, then it combines the interim result table and deletes duplicate rows to form a combined result table working similar as a JOIN.
If the option is to keep the duplicate values, then the UNION ALL keyword should be used.

Note: When including the UNION ALL in the same SQL statement as a UNION operator, however, the result of the operation depends on the order of evaluation. Where there are no parentheses, evaluation is from left to right. Where parentheses are included, the parenthesized subselect is evaluated first, followed, from left to right, by the other parts of the statement.

To test the usage of both keywords, use the example below:

--- To create the objects:

db2 "create table Table1 (A CHAR, B CHAR, C CHAR)"
db2 "create table Table2 (A CHAR, B CHAR, C CHAR)"

db2 "insert into Table1 values( '0' , '0' , '0')"
db2 "insert into Table1 values( '0' , '0' , '0')"
db2 "insert into Table1 values( '1' , '1' , '1')"
db2 "insert into Table1 values( '1' , '1' , '1')"
db2 "insert into Table1 values( '2' , '2' , '2')"
db2 "insert into Table1 values( '2' , '2' , '2')"

db2 "insert into Table2 values( '0' , '0' , '0')"
db2 "insert into Table2 values( '1' , '1' , '1')"
db2 "insert into Table2 values( '2' , '2' , '2')"
db2 "insert into Table2 values( '3' , '3' , '3')"
db2 "insert into Table2 values( '4' , '4' , '4')"

db2 "SELECT * FROM Table1"
db2 "SELECT * FROM Table2"

db2 "SELECT a.A, a.B, a.C FROM Table1 AS a UNION ALL SELECT b.A, b.B, b.C FROM Table2 as b"

--- Results expected:

$ db2 "SELECT * FROM Table1"

A B C
- - -
0 0 0
0 0 0
1 1 1
1 1 1
2 2 2
2 2 2

6 record(s) selected.


$ db2 "SELECT * FROM Table2"

A B C
- - -
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4

5 record(s) selected.


$ db2 "SELECT a.A, a.B, a.C FROM Table1 AS a UNION ALL SELECT b.A, b.B, b.C FROM Table2 as b"

A B C
- - -
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
0 0 0
0 0 0
1 1 1
1 1 1
2 2 2
2 2 2

11 record(s) selected.


$ db2 "SELECT a.A, a.B, a.C FROM Table1 AS a UNION SELECT b.A, b.B, b.C FROM Table2 as b"

A B C
- - -
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4

5 record(s) selected.

[{"Product":{"code":"SSEPGG","label":"Db2 for Linux, UNIX and Windows"},"Business Unit":{"code":"BU058","label":"IBM Infrastructure w\/TPS"},"Component":"Database Objects\/Config - Database","Platform":[{"code":"PF002","label":"AIX"},{"code":"PF010","label":"HP-UX"},{"code":"PF016","label":"Linux"},{"code":"PF027","label":"Solaris"},{"code":"PF033","label":"Windows"}],"Version":"9.7;9.5;9.1;10.1;10.5;11.1","Edition":"","Line of Business":{"code":"LOB10","label":"Data and AI"}}]

Document Information

Modified date:
16 June 2018

UID

swg21621258