Learning navigation

Code with Animation

UNION, INTERSECT & EXCEPT

Stack, overlap and subtract the results of two queries with UNION, INTERSECT and EXCEPT, and know when duplicates stay.

SQL5 min readConcept 17 of 44

Combine rows, not columns

A join makes a table wider. A set operation combines the rows of two queries, one on top of the other. The two queries must return the same number of columns, with compatible types.

UNION stacks them and removes duplicate rows. UNION ALL stacks them and keeps everything. INTERSECT keeps only the rows found in both. EXCEPT keeps the rows of the first query that are not in the second.

Questions about two lists

"Who is in either club?", "Who is in both?" and "Who is only in the first?" are questions about two lists. Each of them has its own operator.

Two clubs, one member in both

SELECT name FROM club_a
UNION
SELECT name FROM club_b;

club_a has Asha, Ben and Chen. club_b has Chen, Dara and Eli. UNION gives 5 names, with Chen once. UNION ALL gives 6 names, with Chen twice. INTERSECT gives only Chen. club_a EXCEPT club_b gives Asha and Ben.

For removing duplicates, two NULL values count as equal, just like in DISTINCT. That is different from a normal comparison, where NULL is never equal to NULL.

Combine two clubs

Press each operator and watch Chen. Then compare the two EXCEPT versions to see why order matters.

SELECT name FROM club_a
UNION
SELECT name FROM club_b;
club_a (3 rows)
nametext
Asha
Ben
Chen
club_b (3 rows)
nametext
Chen
Dara
Eli
Result (5 rows)
nametext
Asha
Ben
Chen
Dara
Eli

UNION stacks both lists and removes duplicates. Chen is in both clubs but appears once.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1`club_a` has 3 names and `club_b` has 3 names, with Chen in both. How many rows does `UNION ALL` return?
  2. 2Which query returns Dara and Eli from the two clubs?
  3. 3Two lists cannot share any rows. Which operator should you use to stack them, and why?

Remember this

  • UNION, INTERSECT and EXCEPT combine the rows of two queries that have the same columns.
  • UNION and INTERSECT and EXCEPT remove duplicates unless you write ALL.
  • EXCEPT depends on order: A minus B is different from B minus A.
  • Columns are matched by position, and ORDER BY at the end sorts the combined result.

Done with this concept?

Mark it complete to track your progress. No login needed.