Sub topic 16
SQL set operations
This chapter covers UNION, INTERSECT and EXCEPT in SQL. It assumes you know basic set operations (union, intersection, difference), the relational algebra versions of these operators, and simple SELECT ... FROM ... WHERE queries. The chapter on DISTINCT and duplicates is also useful background.
What the operators do
SQL set operations combine the results of two SELECT queries into one result. They correspond to the relational algebra operators ∪, ∩ and −.
| SQL operator | Algebra | Rows in the result |
|---|---|---|
| `q1 UNION q2` | q1 ∪ q2 | rows in q1 or q2, or both |
| `q1 INTERSECT q2` | q1 ∩ q2 | rows in both q1 and q2 |
| `q1 EXCEPT q2` | q1 − q2 | rows in q1 that are not in q2 |
Some systems write MINUS instead of EXCEPT. Oracle does this. The meaning is the same.
Union compatibility
Both queries must be union compatible. They must return the same number of columns, and the columns in matching positions must have compatible types. Matching is by position, not by name. The result takes its column names from the first query.
-- Names of all people at the university, students and instructors
SELECT sname AS name FROM Student
UNION
SELECT iname FROM Instructor;If you swap the column order in one query, SQL still combines the columns by position. This can silently mix up unrelated data.
Set semantics versus bag semantics
Plain SELECT returns a bag, which is a collection that can hold duplicates. The set operations behave differently:
UNION,INTERSECTandEXCEPTremove duplicates from the result. They use set semantics.UNION ALL,INTERSECT ALLandEXCEPT ALLkeep duplicates. They use bag semantics.
Suppose A is the bag {1, 1, 2} and B is the bag {1, 3}. Let m be how many times a value appears in A and n how many times it appears in B.
| Expression | Result | Copies of a value in the result |
|---|---|---|
| `A UNION B` | {1, 2, 3} | 1 if it appears in either |
| `A UNION ALL B` | {1, 1, 1, 2, 3} | m + n |
| `A INTERSECT B` | {1} | 1 if it appears in both |
| `A INTERSECT ALL B` | {1} | min(m, n) |
| `A EXCEPT B` | {2} | 1 if m > 0 and n = 0 |
| `A EXCEPT ALL B` | {1, 2} | max(m − n, 0) |
Many systems, including MySQL before version 8.0.31, do not support INTERSECT ALL or EXCEPT ALL. UNION ALL is supported everywhere. It is also faster than UNION, because it skips the duplicate-removal step.
CREATE TABLE A (x INT);
CREATE TABLE B (x INT);
INSERT INTO A VALUES (1), (1), (2);
INSERT INTO B VALUES (1), (3);
SELECT x FROM A UNION ALL SELECT x FROM B; -- 1, 1, 1, 2, 3
SELECT x FROM A UNION SELECT x FROM B; -- 1, 2, 3
SELECT x FROM A EXCEPT SELECT x FROM B; -- 2How NULLs behave
In a WHERE clause, NULL = NULL evaluates to UNKNOWN. Set operations are different. When they decide whether two rows are duplicates, they treat two NULLs as equal. A row (NULL) in both inputs therefore counts as the same row.
-- Suppose P contains (NULL) and (1), and Q contains (NULL) and (2).
SELECT x FROM P INTERSECT SELECT x FROM Q; -- one row: NULL
SELECT x FROM P EXCEPT SELECT x FROM Q; -- one row: 1
SELECT x FROM P UNION SELECT x FROM Q; -- NULL, 1, 2A join on P.x = Q.x would not match the NULLs. This is why INTERSECT and an equi-join can give different answers when NULLs are present.
Precedence and parentheses
INTERSECT binds more tightly than UNION and EXCEPT in the SQL standard. UNION and EXCEPT have equal precedence and are evaluated left to right. Some systems, such as Oracle, historically evaluate all set operators strictly left to right. Use parentheses whenever you mix operators.
-- Standard SQL reads this as: A UNION (B INTERSECT C)
SELECT x FROM A
UNION
SELECT x FROM B
INTERSECT
SELECT x FROM C;
-- Explicit and portable
(SELECT x FROM A UNION SELECT x FROM B)
INTERSECT
SELECT x FROM C;EXCEPT is not commutative: A EXCEPT B is not the same as B EXCEPT A. UNION and INTERSECT are commutative and associative.
Typical query patterns
Use the schema Student(sid, sname, age), Course(cid, cname), Enrolled(sid, cid). Assume courses 101 and 102 exist.
Students enrolled in both courses
SELECT sid FROM Enrolled WHERE cid = 101
INTERSECT
SELECT sid FROM Enrolled WHERE cid = 102;A single condition such as WHERE cid = 101 AND cid = 102 returns nothing, because one row has only one cid. Intersection combines information from two different rows.
Students enrolled in 101 or 102
SELECT sid FROM Enrolled WHERE cid = 101
UNION
SELECT sid FROM Enrolled WHERE cid = 102;This is equivalent to SELECT DISTINCT sid FROM Enrolled WHERE cid = 101 OR cid = 102.
Students enrolled in no course
SELECT sid FROM Student
EXCEPT
SELECT sid FROM Enrolled;This is the same as the NOT EXISTS form from the subquery chapter, but it avoids the NOT IN NULL trap. EXCEPT treats NULLs as equal and does not produce UNKNOWN.
Enrolled in 101 but not 102
SELECT sid FROM Enrolled WHERE cid = 101
EXCEPT
SELECT sid FROM Enrolled WHERE cid = 102;Equivalent forms
Set operations can be rewritten with other constructs. Knowing the rewrites helps with GATE equivalence questions.
| Set operation | Equivalent form |
|---|---|
| `q1 INTERSECT q2` | `SELECT DISTINCT ... FROM q1 WHERE EXISTS (match in q2)` |
| `q1 EXCEPT q2` | `SELECT DISTINCT ... FROM q1 WHERE NOT EXISTS (match in q2)` |
| `q1 UNION q2` | a single query with `OR`, only when both sides use the same table |
For INTERSECT, an IN subquery also works:
SELECT DISTINCT sid
FROM Enrolled
WHERE cid = 101
AND sid IN (SELECT sid FROM Enrolled WHERE cid = 102);The DISTINCT is needed to match the set semantics of INTERSECT. Without it, a student enrolled twice in course 101 could appear twice. In this schema the primary key (sid, cid) prevents that, but the rewrite is not safe in general.
Counting result tuples
GATE questions often ask for the minimum or maximum size of a result. Let |A| and |B| be the numbers of rows.
| Expression | Minimum rows | Maximum rows | Column | Column | Column | Column | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|---|---|---|
| `A UNION ALL B` | \ | A\ | + \ | B\ | \ | A\ | + \ | B\ | ||
| `A UNION B` | max(d(A), d(B)) | d(A) + d(B) | ||||||||
| `A INTERSECT B` | 0 | min(d(A), d(B)) | ||||||||
| `A EXCEPT B` | 0 | d(A) |
Here d(X) is the number of distinct rows in X. If A and B are relations that already hold no duplicates, d(X) equals |X|.
The following diagram shows how to decide which operator and which variant to use.
Common errors
- Writing
WHERE cid = 101 AND cid = 102for "both courses". This returns no rows. UseINTERSECT, a self-join, orGROUP BYwithHAVING COUNT(DISTINCT cid) = 2. - Assuming
UNIONkeeps duplicates. It removes them. UseUNION ALLto keep them. - Combining queries with different column counts or incompatible types. The query fails with an error.
- Putting
ORDER BYin each part. A singleORDER BYgoes at the end and applies to the whole result. It can refer only to column names or positions from the first query. - Mixing operators without parentheses and expecting left-to-right evaluation. The standard gives
INTERSECThigher precedence. - Assuming a join and
INTERSECTagree. They differ on NULLs and on duplicates.
Exercises
Exercise
Table A holds the bag {1, 1, 2, NULL} in one column. Table B holds {1, NULL, NULL, 3}. How many rows does each of these return? (a) A UNION ALL B, (b) A UNION B, (c) A INTERSECT B, (d) A EXCEPT B.
Show answer
(a) 8, since UNION ALL keeps every row (4 + 4). (b) 4, the distinct values 1, 2, 3 and NULL, because set operations treat NULLs as equal. (c) 2, the values 1 and NULL. (d) 1, the value 2.
Exercise
Relation R has 10 rows with no duplicates, and S has 6 rows with no duplicates. Give the minimum and maximum number of rows for R UNION S, R INTERSECT S, and R EXCEPT S.
Show answer
R UNION S: minimum 10 (S is a subset of R), maximum 16 (no overlap). R INTERSECT S: minimum 0, maximum 6. R EXCEPT S: minimum 4 (all of S lies inside R), maximum 10 (no overlap).
Exercise
Write a query for students enrolled in course 101 but not in course 102, using NOT EXISTS instead of EXCEPT. Name one difference in behavior from the EXCEPT version if duplicates were possible in Enrolled.
Show answer
SELECT DISTINCT e1.sid FROM Enrolled e1 WHERE e1.cid = 101 AND NOT EXISTS (SELECT 1 FROM Enrolled e2 WHERE e2.sid = e1.sid AND e2.cid = 102); Without DISTINCT, the NOT EXISTS version could return a student more than once if Enrolled had duplicate rows, while EXCEPT always removes duplicates.