SQL reference (MySQL and MariaDB dialects)

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#

SQL
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#

NameMeaningDefault
UNIONRows of both sides.DISTINCT
EXCEPTRows of the left side that are not on the right.DISTINCT
INTERSECTRows on both sides. Binds tighter than UNION and EXCEPT.DISTINCT
ALLKeep duplicates (with EXCEPT ALL and INTERSECT ALL, by count).off
VALUESA list of rows. Columns are named column_0, column_1 ... in MySQL; MariaDB names them by the first row.none
TABLE tSame 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 BY or LIMIT after 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 / LIMIT is refused (error 1235).
  • MySQL writes VALUES ROW(1, 'a'); MariaDB writes VALUES (1, 'a'). Each dialect refuses the other form.
  • All rows of a VALUES list must have the same width.
  • Privileges: SELECT on every table read.

Examples#

Example (a has 1, 2, 2, 3; b has 2, 3, 3, 4):

SQL
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;

See also#