Skip to content
Part IA Michaelmas Term

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 R(A,B,C)R(A, B, C) and S(A,B,C)S(A, B, C), the set operations are well-formed. If the schemas differ, ρ\rho must be used first to rename columns.

Union (\cup)

RSR \cup S returns all tuples that appear in RR or in SS (or both). Since RA operates on sets, duplicates are eliminated.

RS={ttRtS}R \cup S = \{t \mid t \in R \lor t \in S\}

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 (\cap)

RSR \cap S returns all tuples that appear in both RR and SS.

RS={ttRtS}R \cap S = \{t \mid t \in R \land t \in S\}

SQL.

(SELECT * FROM R)
INTERSECT
(SELECT * FROM S);

Intersection can be expressed in terms of difference:

RS=R(RS)=S(SR)R \cap S = R - (R - S) = S - (S - R)

In practice, SQL’s INTERSECT is clearer and the optimiser will handle the equivalent transformation if needed.

Difference (-)

RSR - S returns all tuples that appear in RR but not in SS.

RS={ttRtS}R - S = \{t \mid t \in R \land t \notin S\}

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: RSSRR - S \neq S - R 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:

ConceptRASQL default
Duplicates?Never (set)Yes (multiset/bag)
Effect on cardinalityProjection may reduce rowsProjection keeps all rows
UNIONEliminates duplicatesEliminates 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:

RR:

AB
1x
2y
3z

SS:

AB
2y
3z
4w

Union RSR \cup S:

AB
1x
2y
3z
4w

Intersection RSR \cap S:

AB
2y
3z

Difference RSR - S:

AB
1x

Difference SRS - R:

AB
4w

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.