Sub topic 13
SQL Set Operations
Assume you know basic SELECT-FROM-WHERE queries, elementary set operations, and that two tables can have different row counts. SQL set operations combine the results of two complete queries.
Union compatibility
Two query results are union-compatible when:
- They have the same number of columns.
- Corresponding columns have compatible data types.
- The columns appear in the same logical order.
The column names in the final result usually come from the first query.
| Operation | Meaning | Duplicate behavior |
|---|---|---|
| `UNION` | Rows in either result | Removes duplicates |
| `UNION ALL` | Rows in either result | Preserves duplicates |
| `INTERSECT` | Rows in both results | Removes duplicates |
| `EXCEPT` | Rows in the first result but not the second | Removes duplicates |
SQL usually treats set-operation results as distinct sets, even though an ordinary SELECT uses bag semantics and can return duplicate rows.
UNION and UNION ALL
Suppose CurrentStudent and Alumni both contain a column named sname:
SELECT sname
FROM CurrentStudent
UNION
SELECT sname
FROM Alumni;This returns each name once. If a name occurs in both tables, it still appears once.
SELECT sname
FROM CurrentStudent
UNION ALL
SELECT sname
FROM Alumni;This keeps every occurrence. If Ravi appears twice in CurrentStudent and once in Alumni, the result contains three Ravi rows.
Use UNION when the question asks for distinct values. Use UNION ALL when occurrences matter or when duplicate removal is not required.
INTERSECT and EXCEPT
INTERSECT returns rows common to both query results:
SELECT sid
FROM Enrolled
WHERE cid = 10
INTERSECT
SELECT sid
FROM Enrolled
WHERE cid = 20;The query finds students enrolled in both courses. It returns each sid at most once.
EXCEPT returns rows produced by the first query that are absent from the second:
SELECT sid
FROM Enrolled
WHERE cid = 10
EXCEPT
SELECT sid
FROM Enrolled
WHERE cid = 20;This finds students enrolled in course 10 but not course 20. The order matters: reversing the two queries asks a different question.
Evaluation and ordering
Parentheses make the intended order clear when several operations are combined. An ORDER BY normally applies to the final combined result:
(
SELECT sid FROM Enrolled WHERE cid = 10
)
UNION
(
SELECT sid FROM Enrolled WHERE cid = 20
)
ORDER BY sid;Without parentheses, precedence rules can vary across SQL implementations. For GATE questions, evaluate the operations according to the stated or standard precedence, and use parentheses when writing an unambiguous query.
Exercise
If the first query returns {1, 1, 2} and the second returns {2, 3}, how many rows result from UNION and UNION ALL?
Show answer
UNION returns 3 rows: {1, 2, 3}. UNION ALL returns 5 rows: {1, 1, 2, 2, 3}.