Set Operations in SQL
Set Operations in SQL (MySQL)
1. Aim
To understand and implement SQL set operations such as UNION, UNION ALL, INTERSECT (simulated), and EXCEPT (simulated) using MySQL.
2. Theory
Set operations in SQL allow combining results from multiple queries into a single result set. They are useful when comparing datasets, finding common or unique values, and merging information from different sources.
2.1 Types of Set Operations
-
UNION
-
Combines results of two SELECT queries.
-
Removes duplicates.
-
-
UNION ALL
-
Combines results of two SELECT queries.
-
Retains duplicates.
-
-
INTERSECT
-
Returns rows common to both queries.
-
MySQL does not support INTERSECT directly, but it can be simulated using
INNER JOINorIN.
-
-
EXCEPT (MINUS)
-
Returns rows from the first query that are not present in the second query.
-
MySQL does not support EXCEPT directly, but it can be simulated using
LEFT JOIN … WHERE NULLorNOT IN.
-
3. Problem Statement
Consider two tables:
-
employees: contains employee IDs and names.
-
contractors: contains contractor IDs and names.
Perform SQL set operations to compare data between the two tables.
4. Table Schema
4.1 Create Tables
4.2 Insert Sample Data
5. SQL Set Operations
5.1 UNION
Removes duplicates from combined result sets.
Output:
| name |
|---|
| Alice |
| Bob |
| Charlie |
| Dave |
| Eve |
5.2 UNION ALL
Includes duplicates.
Output:
| name |
|---|
| Alice |
| Bob |
| Charlie |
| Bob |
| Dave |
| Eve |
5.3 INTERSECT (Simulated using INNER JOIN)
Finds rows common to both tables.
Output:
| name |
|---|
| Bob |
5.4 EXCEPT (Simulated using LEFT JOIN)
Finds rows in employees but not in contractors.
Output:
| name |
|---|
| Alice |
| Charlie |
Alternative using NOT IN:
6. Results
-
Successfully implemented UNION, UNION ALL, and simulated INTERSECT and EXCEPT in MySQL.
-
Observed how MySQL handles set operations and alternatives for unsupported ones.
-
Analyzed differences between removing and retaining duplicates in query outputs.
7. Conclusion
Set operations in SQL allow effective comparison and merging of datasets.
Although MySQL does not directly support INTERSECT and EXCEPT, equivalent results can be achieved using JOINs and subqueries. Understanding these operations is essential for efficient database querying and data analysis.
Comments
Post a Comment