Sub topic 4
Union, Intersection, and Difference
Assume you know basic set operations and can read relation schemas. A relation is treated as a set of tuples in relational algebra, so duplicate tuples are removed automatically.
Union compatibility
Two relations are union-compatible when:
- They have the same number of attributes.
- Corresponding attributes have compatible domains, such as integer with integer.
- Attribute names may differ, but the positions must represent compatible data.
Suppose:
| Relation | Tuples |
|---|---|
| CSEStudents | (1, Asha), (2, Ravi) |
| ECEStudents | (2, Ravi), (3, Meera) |
The relations have the same schema, Student(sid, name), so set operations are valid.
The three operations
Union returns tuples found in either relation. Intersection returns tuples found in both. Difference returns tuples found in the first relation but not the second.
| Operation | Expression | Result |
|---|---|---|
| Union | CSEStudents ∪ ECEStudents | (1, Asha), (2, Ravi), (3, Meera) |
| Intersection | CSEStudents ∩ ECEStudents | (2, Ravi) |
| Difference | CSEStudents − ECEStudents | (1, Asha) |
Union is inclusive: a tuple in both relations appears only once. Difference is directional, so CSEStudents − ECEStudents is generally different from ECEStudents − CSEStudents.
CSEStudents ∪ ECEStudents
CSEStudents ∩ ECEStudents
CSEStudents − ECEStudentsRelational algebra also allows equivalent rewrites. For compatible relations:
R ∩ S = R − (R − S)
R − S = R − (R ∩ S)These identities are useful when an examination question removes one operator.
SQL and duplicate behavior
SQL uses bag semantics by default. A bag can contain duplicate rows. Therefore, SQL UNION removes duplicates, but UNION ALL preserves them. INTERSECT and EXCEPT normally remove duplicates; their ALL forms preserve multiplicities where supported.
SELECT sid, name FROM CSEStudents
UNION
SELECT sid, name FROM ECEStudents;
SELECT sid, name FROM CSEStudents
INTERSECT
SELECT sid, name FROM ECEStudents;
SELECT sid, name FROM CSEStudents
EXCEPT
SELECT sid, name FROM ECEStudents;The SQL queries require compatible column counts and data types. Unlike relational algebra, SQL result order is unspecified unless ORDER BY is used.
A common error is confusing difference with a condition applied to one table. To find CSE students who are not ECE students, both complete relations are needed. Another error is forgetting that UNION removes duplicate rows even when the input query produces them.
Exercise
If R contains {a, b} and S contains {b, c}, what are R ∪ S, R ∩ S, and R − S?
Show answer
R ∪ S = {a, b, c}; R ∩ S = {b}; R − S = {a}.