TExcelTAD
Home › MySQL › MySQL UNION

MySQL UNION

UNION stacks the results of two or more SELECT statements on top of each other. Where a join adds columns from another table, a union adds rows.

sql
SELECT columns FROM table1
UNION
SELECT columns FROM table2;

The rules:

  • every SELECT must return the same number of columns;
  • columns are matched by position, not by name, and should have compatible types;
  • the column names of the result come from the first SELECT.

A contact list from two tables

mysql · try it yourself
SELECT city, country, 'customer' AS kind FROM customers WHERE country = 'UK'
UNION
SELECT city, country, 'supplier' FROM suppliers WHERE country = 'UK';
+------------+---------+----------+
| city       | country | kind     |
+------------+---------+----------+
| London     | UK      | customer |
| Manchester | UK      | customer |
| Edinburgh  | UK      | supplier |
| Leeds      | UK      | supplier |
+------------+---------+----------+

Ben and George both live in London, so their two identical London | UK | customer rows were merged into one.

UNION removes duplicates, UNION ALL keeps them

Plain UNION removes duplicate rows from the combined result (like DISTINCT). UNION ALL keeps everything, and is faster because it doesn't have to look for duplicates:

mysql · try it yourself
SELECT country FROM customers WHERE country IN ('UK', 'Spain')
UNION
SELECT country FROM suppliers WHERE country IN ('UK', 'Spain');

SELECT country FROM customers WHERE country IN ('UK', 'Spain')
UNION ALL
SELECT country FROM suppliers WHERE country IN ('UK', 'Spain');
+---------+
| country |
+---------+
| UK      |
| Spain   |
+---------+
+---------+
| country |
+---------+
| UK      |
| UK      |
| UK      |
| Spain   |
| UK      |
| Spain   |
| UK      |
+---------+

The first result has 2 rows, the second 7 (four customers and three suppliers).

Tip: Use UNION ALL unless you actually need duplicates removed. Removing them means sorting or hashing the whole result.

Sorting a union

An ORDER BY (and LIMIT) at the end applies to the combined result. Use the column names of the first SELECT:

mysql · try it yourself
SELECT name, 'category' AS type FROM categories
UNION ALL
SELECT name, 'supplier' FROM suppliers
ORDER BY name
LIMIT 6;
+--------------------+----------+
| name               | type     |
+--------------------+----------+
| Alpine Dairy Co    | supplier |
| Bakery             | category |
| Beverages          | category |
| CleanHome Supplies | supplier |
| Crunch & Co        | supplier |
| Dairy              | category |
+--------------------+----------+

To sort or limit one part on its own, put it in parentheses: (SELECT ... ORDER BY x LIMIT 3) UNION ALL (SELECT ...).

Building a report with UNION ALL

A union is a handy way to append a total line to a report:

mysql · try it yourself
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
UNION ALL
SELECT 'TOTAL', COUNT(*) FROM orders
ORDER BY status = 'TOTAL', status;
+------------+--------+
| status     | orders |
+------------+--------+
| cancelled  |      2 |
| delivered  |     15 |
| processing |      3 |
| shipped    |      2 |
| TOTAL      |     22 |
+------------+--------+

The ORDER BY sorts the statuses alphabetically but puts the total last: status = 'TOTAL' is 0 for normal rows and 1 for the total. (MySQL can also add total rows with GROUP BY status WITH ROLLUP.)

INTERSECT and EXCEPT

Two related set operators appeared in MySQL 8.0.31: INTERSECT returns rows that occur in both results, and EXCEPT rows of the first result that are not in the second. MariaDB has had them since 10.3:

mysql · try it yourself
SELECT country FROM customers
INTERSECT
SELECT country FROM suppliers
ORDER BY country;
+---------+
| country |
+---------+
| Italy   |
| Spain   |
| UK      |
+---------+

On older MySQL versions, write INTERSECT as an IN/EXISTS subquery and EXCEPT as NOT EXISTS.

Test yourself

What is the difference between UNION and UNION ALL?

  1. UNION ALL removes duplicates
  2. UNION removes duplicates, UNION ALL keeps them
  3. UNION ALL needs the same column names
  4. There is none

Where do the column names of a UNION result come from?

  1. The last SELECT
  2. The first SELECT
  3. Each row's own SELECT
  4. They are numbered

Which query is valid?

  1. SELECT a, b FROM t1 UNION SELECT c FROM t2
  2. SELECT a FROM t1 UNION SELECT c FROM t2
  3. SELECT a FROM t1 UNION ORDER BY a SELECT c FROM t2
  4. UNION SELECT a FROM t1