← Back
LESSON 20
SQL (Core) - Set Operations (UNION & INTERSECT)
Prereq: None | Progress: 0%
Course Syllabus
Lesson 0 📖 What is SQL? Lesson 1 📖 SELECT queries 101 Lesson 2 📖 Queries with constraints (Pt. 1) Lesson 3 📖 Queries with constraints (Pt. 2) Lesson 4 📖 Filtering & sorting results Review 1 📖 Simple SELECT Queries Lesson 6 📖 Multi-table queries with JOINs Lesson 7 📖 OUTER JOINs Lesson 8 📖 A short note on NULLs Lesson 9 📖 Queries with expressions Lesson 10 📖 Queries with aggregates (Pt. 1) Lesson 11 📖 Queries with aggregates (Pt. 2) Lesson 12 📖 Order of execution of a Query Lesson 13 📖 Inserting rows Lesson 14 📖 Updating rows Lesson 15 📖 Deleting rows Lesson 16 📖 Creating tables Lesson 17 📖 Altering tables Lesson 18 📖 Dropping tables Lesson 19 📖 Subqueries & Nested Queries Lesson 20 📖 Set Operations Summary 🎓 Course Completion
SQL Lesson 20: Set Operations
Set operations allow you to combine or subtract result sets from two or more SELECT queries into a single unified result.
1. UNION, INTERSECT, and EXCEPT Operators
- UNION: Combines distinct rows from both queries (automatically eliminates duplicates).
- UNION ALL: Combines all rows from both queries (retains duplicate rows for max speed).
- INTERSECT: Returns only rows present in both query result sets.
- EXCEPT (MINUS): Returns rows from the first query that do not exist in the second.
SELECT building_name FROM buildings
UNION
SELECT building FROM employees WHERE building IS NOT NULL;
2. Set Operation Compatibility Rules
To perform a set operation, both SELECT statements must return the exact same number of columns in the same order, and corresponding columns must have compatible data types.
🗄️ Schema Explorer SELECTABLE
› movies
|
🎯 Exercises Checklist:
☐ 1. Find all unique building names from both buildings and employees tables using UNION
☐ 2. Find buildings listed in buildings table that have no employees assigned using EXCEPT
⚡ Practice Console
💡 Hint:
Loading hint...
🔑 Solution SQL:
SELECT * FROM movies; Data Output
No results. Run query to fetch data.