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
SELECT name, 'student' AS role FROM studentsUNION -- removes duplicate rowsSELECT name, 'mentor' AS role FROM mentors;SELECT city FROM studentsUNION ALL -- keeps duplicates (faster)SELECT city FROM mentors;
INTERSECT & EXCEPT
SELECT email FROM studentsINTERSECT -- rows in bothSELECT email FROM alumni;SELECT email FROM studentsEXCEPT -- in the first, not the secondSELECT email FROM unsubscribed;
Key takeaways
- 01Set operations stack query results vertically (joins add columns sideways).
- 02UNION combines and de-duplicates; UNION ALL keeps duplicates and is faster.
- 03INTERSECT returns rows in both; EXCEPT returns rows in the first not the second.
- 04Both queries must return the same columns with compatible types.
