Relational Algebra: Union, Intersection, and Difference
Union-compatible schemas
For union, intersection, and difference to be defined, the two relations must have union-compatible schemas: the same number of columns, with the same column names and the same (or compatible) domain types.
Given and , the set operations are well-formed. If the schemas differ, must be used first to rename columns.
Union ()
returns all tuples that appear in or in (or both). Since RA operates on sets, duplicates are eliminated.
SQL.
(SELECT * FROM R)
UNION
(SELECT * FROM S);
SQL’s UNION eliminates duplicates by default (set semantics). To keep duplicates, use the non-standard UNION ALL.
Intersection ()
returns all tuples that appear in both and .
SQL.
(SELECT * FROM R)
INTERSECT
(SELECT * FROM S);
Intersection can be expressed in terms of difference:
In practice, SQL’s INTERSECT is clearer and the optimiser will handle the equivalent transformation if needed.
Difference ()
returns all tuples that appear in but not in .
SQL.
(SELECT * FROM R)
EXCEPT
(SELECT * FROM S);
Note: SQL uses the keyword EXCEPT rather than MINUS (some other database systems use MINUS).
Difference is not commutative: in general.
Set semantics vs multiset semantics
The RA operators work over sets of tuples. A tuple that appears multiple times in a source table appears at most once in the RA result. This is a key distinction:
| Concept | RA | SQL default |
|---|---|---|
| Duplicates? | Never (set) | Yes (multiset/bag) |
| Effect on cardinality | Projection may reduce rows | Projection keeps all rows |
UNION | Eliminates duplicates | Eliminates duplicates (but UNION ALL keeps them) |
SQL defaults to multiset (bag) semantics. The DISTINCT keyword forces set semantics. This distinction is covered in detail in Lecture 7. For now, assume that SQL queries in these notes use SELECT DISTINCT where needed to match RA set behaviour.
Worked example
Given relations:
:
| A | B |
|---|---|
| 1 | x |
| 2 | y |
| 3 | z |
:
| A | B |
|---|---|
| 2 | y |
| 3 | z |
| 4 | w |
Union :
| A | B |
|---|---|
| 1 | x |
| 2 | y |
| 3 | z |
| 4 | w |
Intersection :
| A | B |
|---|---|
| 2 | y |
| 3 | z |
Difference :
| A | B |
|---|---|
| 1 | x |
Difference :
| A | B |
|---|---|
| 4 | w |
Summary
- Union, intersection, and difference require union-compatible schemas.
- All three eliminate duplicates in RA (set semantics).
- SQL:
UNION,INTERSECT,EXCEPT. - Difference is non-commutative; intersection can be expressed via difference.