UNION, INTERSECT, EXCEPT
156 min
Sometimes you need to combine the results of several queries into one list, or compare them with each other. That is what set operations do.
The condition: matching columns
The combined queries must have the same number of columns with compatible types. The column names of the result come from the first query.
UNION and UNION ALL
Everyone at the university — students and teachers — in one list:
university
UNION ALLadds everything, duplicates included (faster);UNIONremoves duplicates.
university
INTERSECT — in both
Last names that appear among students and among teachers:
university
EXCEPT — in the first, not in the second
Last names found among students but not among teachers:
university
1Exercise
Show, in one list without repeats, every city that appears among customers (customers.city) and in orders (orders.city).
2Exercise
Show the customer_id of the customers who placed orders but never wrote a review (use EXCEPT).
Remember
UNION ALLadds,UNIONadds without duplicates.INTERSECTis the overlap,EXCEPTis the difference.- The queries must have the same number and types of columns.