UNION
Overview
TheUNION
combines the result sets of 2 or more select statements, removing duplicate rows between the tables.
Syntax
Below is the syntax of theUNION
:
-
value1, value2, ... value_n
: The columns you wish to retrieve. You can also retrieve all the values using theSELECT * FROM
query. -
table1, table2
: The tables that you wish to retrieve records from.
Things to consider:
1. The data types of corresponding columns in the
2. The order of columns is flexible as long as the columns in consecutive places are pairwise compatible. For example, you can do
1. The data types of corresponding columns in the
SELECT
queries must be compatible. 2. The order of columns is flexible as long as the columns in consecutive places are pairwise compatible. For example, you can do
SELECT col1, col2 FROM table1 UNION SELECT col2, col1 FROM table2
.Example
Let’s consider an example of theUNION
. Assume we have a table called employees
and another table called contractors
. We want to retrieve a combined list of names from both tables, excluding duplicates:
SELECT
statement:


UNION ALL
Overview
TheUNION ALL
combines the result sets of 2 or more select statements, returning all rows from the query and not removing duplicate rows between the tables.
Syntax
Below is the syntax of theUNION ALL
:
value1, value2, ... value_n
: The columns you wish to retrieve. You can also retrieve all the values using theSELECT * FROM
query.table1, table2
: The tables that you wish to retrieve records from.
Things to consider:
1. The data types of corresponding columns in the
2. The order of columns is flexible as long as the columns in consecutive places are pairwise compatible.
1. The data types of corresponding columns in the
SELECT
queries must be compatible. 2. The order of columns is flexible as long as the columns in consecutive places are pairwise compatible.
Example
Suppose you have two separate tables,sales_2022
and sales_2023
, containing sales data for different years. You want to combine the sales data from both tables to get a complete list of sales transactions without removing duplicates.
SELECT
statement:
UNION ALL
:
UNION ALL
, all values are displayed, including the duplicate ones.

