Relational Algebra: Product and Renaming
Product ()
The RA product is based on the Cartesian product but adapted for database relations. Given and , the product returns a relation over the combined attributes .
Mathematically, the Cartesian product of two relations (as sets of tuples) would return pairs of tuples:
The RA product instead returns tuples formed by concatenating the fields of each pair:
where denotes tuple concatenation.
Example. Suppose:
:
| A | B |
|---|---|
| 1 | x |
| 2 | y |
:
| C | D |
|---|---|
| p | 10 |
| q | 20 |
:
| A | B | C | D |
|---|---|---|---|
| 1 | x | p | 10 |
| 1 | x | q | 20 |
| 2 | y | p | 10 |
| 2 | y | q | 20 |
If has rows and has rows, the product has rows.
Column name disjointness
A critical constraint: the schemas of and must have disjoint column names. If both relations have a column called id, the product would have two columns both called id, which is not a valid relation.
When column names overlap, renaming is required first. For example, if and share column :
produces , and then:
produces a valid relation over .
SQL translations
There are two equivalent SQL formulations of the product:
Explicit syntax (preferred).
SELECT A, B, C, D
FROM R CROSS JOIN S;
Implicit syntax (comma-separated tables).
SELECT A, B, C, D
FROM R, S;
Both produce the same result. The CROSS JOIN form makes the intent more explicit.
The product is rarely used alone
The product itself is of limited practical use. Its value comes from combining it with selection to form a join. Selecting the product rows where matching columns are equal gives the natural join or equi-join:
This pattern is so common that SQL provides a dedicated JOIN ... ON syntax, and RA has the derived (natural join) operator (see following note).
Combining product with renaming
When writing RA expressions involving product, the standard pattern is:
- Rename overlapping columns in one or both sub-queries with .
- Apply to the renamed sub-queries.
- Apply to select matching rows.
- Apply to remove duplicate columns.
Example. Find all pairs of students and lecturers in the same college:
But this is verbose. The natural join (next note) simplifies it.
Summary
- concatenates tuples; the result has rows.
- Column names of and must be disjoint; use when they overlap.
- SQL:
CROSS JOINor comma-separated tables inFROM. - The product is typically combined with selection to form a join.