Skip to main content
Albero Academy

UNION & Set Operations

Stack query results vertically with UNION, INTERSECT, EXCEPT.

Joins & Combining7 min

Joins combine tables sideways (adding columns). Set operations combine query results vertically (stacking rows). UNION is the common one; both queries must have matching columns.

UNION

stack results
SELECT name, 'student' AS role FROM students
UNION -- removes duplicate rows
SELECT name, 'mentor' AS role FROM mentors;
SELECT city FROM students
UNION ALL -- keeps duplicates (faster)
SELECT city FROM mentors;

INTERSECT & EXCEPT

common and difference
SELECT email FROM students
INTERSECT -- rows in both
SELECT email FROM alumni;
SELECT email FROM students
EXCEPT -- in the first, not the second
SELECT email FROM unsubscribed;

Key takeaways

  1. 01Set operations stack query results vertically (joins add columns sideways).
  2. 02UNION combines and de-duplicates; UNION ALL keeps duplicates and is faster.
  3. 03INTERSECT returns rows in both; EXCEPT returns rows in the first not the second.
  4. 04Both queries must return the same columns with compatible types.

Finished this chapter?

Mark it complete to track your progress through SQL.