Skip to content

MySQL Union

The UNION operator in MySQL is used to combine the results of two or more SELECT queries into a single result set. The combined result set includes all rows from the individual queries, but by default, it removes duplicate rows. If you want to retain duplicates, you can use UNION ALL instead.

  • used to combine the result-set of two or more SELECT statements
  • Every SELECT statement within UNION must have the same number of columns
  • The columns must also have similar data types
  • The columns in every SELECT statement must also be in the same order
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
ORDER BY columan_name; //Optional

Using UNION to Combine Results

SELECT first_name, last_name FROM employees
WHERE department = 'Sales'
UNION
SELECT first_name, last_name FROM employees
WHERE department = 'Marketing;

Using UNION ALL to Include Duplicates

SELECT first_name, last_name FROM employees
WHERE department = 'Sales'
UNION ALL
SELECT first_name, last_name FROM employees
WHERE department = 'Marketing';