Sub topic 6
Joins: Theta, Equi, Natural, and Outer
Assume you know relations, Cartesian products, selection, projection, and basic SQL SELECT statements. A join combines related tuples from two relations. In relational algebra, a join is usually built from a Cartesian product followed by a condition.
Theta joins
A theta join uses any comparison condition, such as =, <, >, <=, or <>.
\[ R \bowtie{\theta} S = \sigma{\theta}(R \times S) \]
For example, suppose:
Student(sid, name, age)Course(cid, title, min_age)
To pair each student with courses whose minimum age the student satisfies:
\[ Student \bowtie{Student.age \ge Course.min\age} Course \]
The condition may use attributes from both relations. If both relations contain an attribute with the same name, qualify it with the relation name.
Equi-joins
An equi-join is a theta join whose condition uses only equality. For enrollment data:
Student(sid, name)Enrolled(sid, cid)
\[ Student \bowtie_{Student.sid = Enrolled.sid} Enrolled \]
The result contains both copies of the matching sid attribute. SQL expresses the same condition with ON.
SELECT s.sid, s.name, e.cid
FROM Student AS s
JOIN Enrolled AS e
ON s.sid = e.sid;Natural joins
A natural join automatically matches all attributes with the same name and removes the duplicate copy from the result.
\[ Student \bowtie Enrolled \]
If sid is the only common attribute, this is equivalent to the equi-join on sid, followed by removing one copy of sid.
| Join | Matching rule | Duplicate join columns |
|---|---|---|
| Theta join | Any comparison condition | Usually retained |
| Equi-join | Equality condition | Usually retained |
| Natural join | All same-named attributes | Removed |
Natural joins are concise but fragile. Adding an unrelated same-named column to either relation can silently change the result. Named JOIN ... ON conditions are usually safer in SQL.
Outer joins
An inner join returns only matching pairs. An outer join also preserves tuples that have no match.
- A left outer join preserves every tuple from the left relation.
- A right outer join preserves every tuple from the right relation.
- A full outer join preserves tuples from both sides.
Missing attributes are filled with NULL.
SELECT s.sid, s.name, e.cid
FROM Student AS s
LEFT OUTER JOIN Enrolled AS e
ON s.sid = e.sid;A student with no enrollment still appears, with e.cid equal to NULL. A condition placed in WHERE can accidentally remove such rows:
SELECT s.sid, e.cid
FROM Student AS s
LEFT JOIN Enrolled AS e ON s.sid = e.sid
WHERE e.cid = 10;This behaves like an inner join for that condition. Put a matching restriction in ON when unmatched left rows must remain.
Exercise
Student has rows (1, A) and (2, B). Enrolled has only (1, 10). How many rows does Student LEFT JOIN Enrolled ON Student.sid = Enrolled.sid return?
Show answer
Two rows. Student 1 matches enrollment 10, and student 2 remains with NULL in the Enrolled columns.