Learn UNION, UNION ALL, INTERSECT, EXCEPT / MINUS with
Master SQL set operations in this beginner-friendly guide. Learn how to combine query results using UNION, UNION ALL, INTERSECT, and EXCEPT/MINUS. Practice merging student tables and finding common employees in multiple departments.
1. Introduction
Set operations in SQL allow you to combine results from multiple queries into a single result set.
- Useful for merging datasets or finding common/different records.
- Each query must return the same number of columns with compatible data types.
2. UNION and UNION ALL
2.1 UNION
- Combines results of two queries removing duplicates.
Syntax:
Example:
2.2 UNION ALL
- Combines results including duplicates.
Example:
3. INTERSECT
- Returns only rows common to both queries.
Syntax:
Example:
4. EXCEPT / MINUS
- Returns rows from the first query not in the second.
- SQL Server uses EXCEPT, Oracle/PostgreSQL uses MINUS.
Syntax (SQL Server):
Example:
Example (Oracle/PostgreSQL):
5. Practical Exercises
- Merge two student tables into one list using UNION.
- Merge two student tables including duplicates using UNION ALL.
- Find employees present in both Department A and Department B using INTERSECT.
- List employees in Department A but not in Department B using EXCEPT / MINUS.
- Compare product lists from two regions to find common and unique products.
6. Tips for Beginners
- Ensure column count and data types match in both queries.
- Use UNION to remove duplicates, UNION ALL to keep duplicates.
- Use INTERSECT for common data, EXCEPT/MINUS for differences.
- Set operations are performed after WHERE and GROUP BY clauses in individual queries.
Next Step: After mastering set operations, the next module is Indexing and Performance, where you’ll learn about indexes, query optimization, and execution plans to improve database efficiency.