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

2023-06-20

Docshowtosnippetops

UNION and UNION ALL are both used to combine the result sets of two or more SELECT statements into a single result.

UNION will remove duplicate rows from the result set, whereas UNION ALL will include duplicates

#Example

Table_A

ID Name
1 Alice
2 Bob
3 Carol

Table_B

ID Name
2 Bob
3 Carol
4 David
SELECT * FROM Table_A
UNION
SELECT * FROM TABLE_B

gives:

ID Name
1 Alice
2 Bob
3 Carol
4 David
SELECT * FROM Table_A
UNION ALL
SELECT * FROM TABLE_B

gives (notice duplicates):

ID Name
1 Alice
2 Bob
3 Carol
2 Bob
3 Carol
4 David