Purpose
You can use this statement to perform the UNION, EXCEPT, or INTERSECT operation on the query results of the SELECT statement.
Syntax
select_clause_set:
select_clause_set_left [ UNION | UNION ALL | MINUS | EXCEPT | INTERSECT] select_clause_set_right
[sort_list_columns] [limit_clause]
Parameters
| Parameter | Description |
|---|---|
| select_clause_set_left | The SELECT statement that returns the left set used for set calculation. |
| select_clause_set_right | The SELECT statement that returns the right set used for set calculation. |
| sort_list_columns | The grouping method to be used after the set calculation. |
| limit_clause | The number of rows to be returned after the set calculation. |
| UNION ALL | Combines the results of two queries. |
| UNION | Combines the results of two queries and removes the duplicates. |
| MINUS | EXCEPT | Returns unique rows from the result set of the query on the left side of the operator that do not exist in the result set of the query on the right side. Note: MINUS is a synonym for EXCEPT. |
| INTERSECT | Returns unique rows that exist in the result sets of both the query on the left side and the one on the right side of the operator. |
Examples
Take the following two tables as an example:
obclient> CREATE TABLE t1 (c1 INT, c2 INT);
obclient> CREATE TABLE t2 (c1 INT, c2 INT);
obclient> INSERT INTO t1 VALUES (1, -1), (2, -2);
obclient> INSERT INTO t2 VALUES (1, 1), (2, -2), (3, 3);
Query all records of dataset
t1∪t2.obclient> SELECT c1, c2 FROM t1 UNION ALL SELECT c1, c2 FROM t2; +------+------+ | c1 | c2 | +------+------+ | 1 | -1 | | 2 | -2 | | 1 | 1 | | 2 | -2 | | 3 | 3 | +------+------+ 5 rows in setQuery all unique records of dataset
t1∪t2.obclient> SELECT c1, c2 FROM t1 UNION SELECT c1, c2 FROM t2; +------+------+ | c1 | c2 | +------+------+ | 1 | -1 | | 2 | -2 | | 1 | 1 | | 3 | 3 | +------+------+ 4 rows in setQuery the intersection of
t1andt2.obclient> SELECT c1, c2 FROM t1 INTERSECT SELECT c1, c2 FROM t2; +------+------+ | c1 | c2 | +------+------+ | 2 | -2 | +------+------+ 1 row in setQuery the records that exist in only one of
t1andt2.obclient> SELECT c1, c2 FROM t1 EXCEPT SELECT c1, c2 FROM t2; +------+------+ | c1 | c2 | +------+------+ | 1 | -1 | +------+------+ 1 row in setQuery the first two rows sorted in descending order by
c2in the union oft1andt2.obclient> SELECT c1, c2 FROM t1 UNION SELECT c1, c2 FROM t2 ORDER BY c2 DESC LIMIT 2; +------+------+ | c1 | c2 | +------+------+ | 3 | 3 | | 1 | 1 | +------+------+ 2 rows in set