In MySQL, the UNION operator is used to combine the results of two or more SELECT statements into a single result set. It removes duplicate rows by default.
Here's the basic syntax of the UNION operator:
SELECT columns
FROM table1
WHERE condition1
UNION
SELECT columns
FROM table2
WHERE condition2;
Suppose we have two tables: customers and suppliers. Both tables have the same structure with columns name and city. We want to retrieve a list of all unique names and cities from both tables.
SELECT name, city FROM customers
UNION
SELECT name, city FROM suppliers;
In this query:
If you want to include duplicate rows in the result set, you can use the UNION ALL operator instead of UNION. UNION ALL does not remove duplicate rows.
SELECT name, city FROM customers
UNION ALL
SELECT name, city FROM suppliers;
In this query, the result set will include all rows from both tables, including duplicates.
The UNION operator is useful when you want to combine the results of multiple queries into a single result set, especially when dealing with similar data structures across different tables.