UNION, EXCEPT, INTERSECT, VALUES and TABLE
Set operations over query results, the VALUES and TABLE statements, and how ORDER BY and LIMIT attach to them.
A query expression joins SELECTs (and parenthesised queries, VALUES lists and TABLE statements) with set operators.
Syntax#
query_expression:
query_term [ { UNION | EXCEPT } [ALL | DISTINCT] query_term ] ...
[ORDER BY expr [ASC | DESC] [, ...]]
[LIMIT { row_count | offset, row_count | row_count OFFSET offset }]
query_term:
query_primary [ INTERSECT [ALL | DISTINCT] query_primary ] ...
query_primary:
SELECT ...
| ( query_expression )
| VALUES ROW(value, ...) [, ROW(value, ...)] ... -- MySQL
| VALUES (value, ...) [, (value, ...)] ... -- MariaDB
| TABLE tbl_name [ORDER BY ...] [LIMIT ...]Arguments#
| Name | Meaning | Default |
|---|---|---|
UNION | Rows of both sides. | DISTINCT |
EXCEPT | Rows of the left side that are not on the right. | DISTINCT |
INTERSECT | Rows on both sides. Binds tighter than UNION and EXCEPT. | DISTINCT |
ALL | Keep duplicates (with EXCEPT ALL and INTERSECT ALL, by count). | off |
VALUES | A list of rows. Columns are named column_0, column_1 ... in MySQL; MariaDB names them by the first row. | none |
TABLE t | Same as SELECT * FROM t. | none |
Remarks#
- The column names of the result are those of the first query. Sides with a different number of columns are an error (1222).
- An
ORDER BYorLIMITafter the last term, when that term is parenthesised, belongs to the whole expression. A second one on the whole is a syntax error. VALUES ... ORDER BY/LIMITis refused (error 1235).- MySQL writes
VALUES ROW(1, 'a'); MariaDB writesVALUES (1, 'a'). Each dialect refuses the other form. - All rows of a
VALUESlist must have the same width. - Privileges:
SELECTon every table read.
Examples#
Example (a has 1, 2, 2, 3; b has 2, 3, 3, 4):
SELECT x FROM a UNION SELECT x FROM b ORDER BY x; -- 1 2 3 4
SELECT x FROM a UNION ALL SELECT x FROM b ORDER BY x; -- 1 2 2 2 3 3 3 4
SELECT x FROM a EXCEPT SELECT x FROM b ORDER BY x; -- 1
SELECT x FROM a INTERSECT SELECT x FROM b ORDER BY x; -- 2 3
(SELECT 1 AS a) UNION (SELECT 2) ORDER BY a DESC LIMIT 1; -- 2
VALUES ROW(1, 'a'), ROW(2, 'b');
TABLE a ORDER BY x LIMIT 2;