UNION Keyword
The result set from two or more SELECT operations is combined by the UNION command but only distinct values.
There are two basic rules are followed when you want to use Union Keyword or Union All.
- All queries must have the same amount of columns and column ordering.
- Each query requires that the data types of the columns on the involving table be the same or compatible.
Syntax
SELECT <COLUMN1>,<COLUMN2> FROM <TABLE1>
UNION
SELECT <COLUMN1>,<COLUMN2> FROM <TABLE2>
Example
SELECT Name FROM Employee
UNION
SELECT Name FROM Worker
In the above example, it returns only unique names from both tables.
UNION ALL Keyword
The result set from two or more SELECT operations is combined by the UNION ALL command, and it also allows duplicate values.
Syntax
SELECT <COLUMN1>,<COLUMN2> FROM <TABLE1>
UNION ALL
SELECT <COLUMN1>,<COLUMN2> FROM <TABLE2>
Example
SELECT Name FROM Employee
UNION ALL
SELECT Name FROM Worker
In the above example, it returns all names from both tables, and if names are duplicates, it also returns.
Summary
The UNION and UNION ALL command combine the result set of two or more SELECT statements.