Assignment: SQL Set Operations
1. Introduction
Set operations in SQL allow users to combine and manipulate the result sets of multiple SELECT
queries using principles of set theory. They help analyze, merge, and filter data from different
sources without using joins. The four primary SQL set operations are UNION, INTERSECT,
EXCEPT (or MINUS), and UNION ALL.
2. Types of Set Operations in SQL
1. UNION
- Combines result sets of two or more SELECT queries.
- Removes duplicate rows by default.
Example:
Tables:
Customers
1 Alice
2 Bob
Suppliers
101 SupplierA
102 SupplierB
Query:
SELECT CustomerName FROM Customers
UNION
SELECT SupplierName FROM Suppliers;
Result:
Alice
Bob
SupplierA
SupplierB
2. INTERSECT
- Returns only the common rows appearing in both result sets.
Example:
SELECT CustomerName FROM Customers
INTERSECT
SELECT SupplierName FROM Suppliers;
Result: (Empty)
3. EXCEPT / MINUS
- Returns rows from the first query that do not appear in the second.
Example:
SELECT CustomerName FROM Customers
EXCEPT
SELECT SupplierName FROM Suppliers;
Result:
Alice
Bob
4. UNION ALL
- Similar to UNION but keeps duplicates.
Example:
SELECT CustomerName FROM Customers
UNION ALL
SELECT SupplierName FROM Suppliers;
Result:
Alice
Bob
SupplierA
SupplierB
3. Difference Between Set Operations and Joins
Set operations combine full result sets, requiring equal number and type of columns, while joins
combine related tables based on conditions. Set operations handle duplicates automatically,
whereas joins depend on join type and data.
4. Conclusion
Set operations offer an efficient way to combine, intersect, or subtract results from multiple queries,
complementing joins for relational data analysis.