The basic syntax of UNION
is:
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
SELECT
: The queries you want to combine.column1, column2, ...
: The columns to select from each table (must be the same in both queries).UNION
: Combines the results of the two queries, removing duplicates.Let’s assume we have two tables: employees_2023
and employees_2024
. Both tables have the same structure and store employee names. We want to retrieve a list of unique employee names from both years. Here’s the query:
SELECT name FROM employees_2023
UNION
SELECT name FROM employees_2024;
In this example:
name
column from both employees_2023
and employees_2024
.UNION
ensures that only distinct employee names are returned.SELECT
statements.UNION
removes duplicate rows. If you want to keep duplicates, use UNION ALL
.The UNION
operator in MySQL is an efficient way to combine results from multiple SELECT
queries into one result set while ensuring unique rows. It’s particularly useful when you need to merge data from similar tables or queries. Understanding how to use UNION
and UNION ALL
helps in managing and manipulating your data more effectively.