UNION
combines the result sets of 2 or more select statements, removing duplicate rows between the tables.
UNION
:
value1, value2, ... value_n
: The columns you wish to retrieve. You can also retrieve all the values using the SELECT * FROM
query.
table1, table2
: The tables that you wish to retrieve records from.
SELECT
queries must be compatible. SELECT col1, col2 FROM table1 UNION SELECT col2, col1 FROM table2
.UNION
. 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
combines the result sets of 2 or more select statements, returning all rows from the query and not removing duplicate rows between the tables.
UNION ALL
:
value1, value2, ... value_n
: The columns you wish to retrieve. You can also retrieve all the values using the SELECT * FROM
query.table1, table2
: The tables that you wish to retrieve records from.SELECT
queries must be compatible. 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.