SQL Set Operations: INTERSECT, UNION, UNION ALL, EXCEPT
Step 1: Create Tables
CREATE TABLE CourseA (
student_id INT,
student_name VARCHAR(50)
);
CREATE TABLE CourseB (
student_id INT,
student_name VARCHAR(50)
);
Step 2: Insert Data
INSERT INTO CourseA VALUES
(1, 'Ali'),
(2, 'Sara'),
(3, 'Ahmed'),
(4, 'Fatima');
INSERT INTO CourseB VALUES
(3, 'Ahmed'),
(4, 'Fatima'),
(5, 'Zain'),
(6, 'Hira');
INTERSECT
Returns only common rows between two SELECT queries.
SQL Set Operations: INTERSECT, UNION, UNION ALL, EXCEPT
SELECT * FROM CourseA
INTERSECT
SELECT * FROM CourseB;
Output:
student_id | student_name
-----------|--------------
3 | Ahmed
4 | Fatima
UNION
Combines results from both SELECT queries and removes duplicates.
SELECT * FROM CourseA
UNION
SELECT * FROM CourseB;
Output:
student_id | student_name
-----------|--------------
1 | Ali
2 | Sara
3 | Ahmed
4 | Fatima
5 | Zain
6 | Hira
UNION ALL
SQL Set Operations: INTERSECT, UNION, UNION ALL, EXCEPT
Combines results from both SELECTs and keeps duplicates.
SELECT * FROM CourseA
UNION ALL
SELECT * FROM CourseB;
Output:
student_id | student_name
-----------|--------------
1 | Ali
2 | Sara
3 | Ahmed
4 | Fatima
3 | Ahmed
4 | Fatima
5 | Zain
6 | Hira
EXCEPT
Returns rows from the first query not present in the second.
SELECT * FROM CourseA
EXCEPT
SELECT * FROM CourseB;
Output:
student_id | student_name
-----------|--------------
SQL Set Operations: INTERSECT, UNION, UNION ALL, EXCEPT
1 | Ali
2 | Sara
Note:
- Columns in both SELECT statements must have the same number and data types.
- INTERSECT, UNION, and EXCEPT remove duplicates by default.
- UNION ALL includes duplicates.