UNION, INTERSECT, and EXCEPT
- Capella Operational
- reference
Return Values
UNION
, INTERSECT
, and EXCEPT
return distinct results, such that there are no duplicates.
UNION ALL
, INTERSECT ALL
, and EXCEPT ALL
return all applicable values, including duplicates.
These queries are faster, because they do not compute distinct results.
You can improve the performance of a query by using covering indexes, where the index includes all the information needed to satisfy the query. For more information, see Covering Indexes.
To order all the results of a set operator together, refer to the examples for the ORDER BY clause.
Examples
To try the examples in this section, set the query context to the inventory
scope in the travel sample dataset.
For more information, see Query Context.
For the following examples, consider these queries and the number of results they return.
SELECT DISTINCT city FROM airport;
(1641 results)
SELECT DISTINCT city FROM hotel;
(274 results)
The SELECT statements in the following examples do not need to use the DISTINCT keyword, since the set operators return distinct results when used without the ALL keyword.
|
SELECT city FROM airport
UNION
SELECT city FROM hotel;
This gives 1871 results:
[
{
"city": "Calais"
},
{
"city": "Peronne"
},
{
"city": "Nangis"
},
{
"city": "Bagnole-de-l'orne"
},
// ...
]
SELECT city FROM airport
INTERSECT
SELECT city FROM hotel;
This gives 44 results:
[
{
"city": "Cannes"
},
{
"city": "Nice"
},
{
"city": "Orange"
},
{
"city": "Avignon"
},
// ...
]
SELECT city FROM airport
EXCEPT
SELECT city FROM hotel;
This gives 1597 results:
[
{
"city": "Calais"
},
{
"city": "Peronne"
},
{
"city": "Nangis"
},
{
"city": "Bagnole-de-l'orne"
},
// ...
]
SELECT city FROM hotel
EXCEPT
SELECT city FROM airport;
This gives 230 results:
[
{
"city": "Medway"
},
{
"city": "Gillingham"
},
{
"city": "Giverny"
},
{
"city": "Highland"
},
// ...
]