You can use the UNION, INTERSECT, and EXCEPT operators to combine multiple query result sets to a single result set.
Syntax
query
{ UNION [ ALL ] | INTERSECT | EXCEPT }
query Parameters
UNION: returns the union of two result sets.UNION ALL: returns the union of two result sets with duplicate rows retained. TheALLkeyword indicates that the duplicate rows are retained after theUNIONcalculation.INTERSECT: returns the intersection of two result sets.EXCEPT: returns rows that appear in the first result set, but not in the other result set.
Calculation sequence
- The
UNIONandEXCEPToperators are left-associative. That is, if you do not use parentheses () to change the calculation sequence, the calculation starts from left to right.For example, in the following statement, the
UNIONoperator returns the union ofT1andT2. Then, theEXCEPToperator returns the rows that appear only in the union returned by theUNIONoperator, but not T3.select * from t1 union select * from t2 except select * from t3 order by c1; - In the same statement, the
INTERSECToperator is prioritized over theUNIONandEXCEPToperators.For example, the following statement finds the intersection of
T2andT3, and then the union of the intersection andT1.select * from t1 union select * from t2 intersect select * from t3 order by c1; - You can use parentheses () to change the calculation sequence of these operators.
For example, the following statement finds the union of
T1andT2, and then the intersection of the union andT3.(select * from t1 union select * from t2) intersect (select * from t3) order by c1;