Sub topic 12
SQL Joins
Prerequisites and working model
Assume you know tables, rows, columns, primary keys, and basic SELECT-FROM-WHERE queries. A join combines rows from two or more tables using a matching condition. The result contains columns from the joined tables.
Consider these relations:
| Student(sid, sname) | Enrolled(sid, cid) | Course(cid, cname) |
|---|---|---|
| `(1, Ana)` | `(1, 10)` | `(10, DBMS)` |
| `(2, Ben)` | `(1, 20)` | `(20, OS)` |
| `(3, Chen)` | `(3, 10)` | `(30, Networks)` |
The common attributes, such as sid or cid, connect related tuples.
Inner joins
An inner join returns only pairs that satisfy its condition. In relational algebra, a theta join is:
Student ⋈ Student.sid = Enrolled.sid Enrolled
The condition may use any comparison, such as =, <, or >. An equi-join is a theta join whose condition uses equality.
SQL writes the same idea as follows:
SELECT s.sid, s.sname, e.cid
FROM Student AS s
JOIN Enrolled AS e
ON s.sid = e.sid;The aliases s and e give shorter names to the tables. This query returns Ana and Chen because they have enrollment rows. Ben is absent because no matching row exists in Enrolled.
A natural join matches columns with the same name automatically and keeps one copy of the matching column. It can be convenient, but it is risky when unrelated columns happen to share a name. An explicit ON condition is usually clearer.
Outer joins
An outer join preserves unmatched rows. A left outer join keeps every row from its left table and fills missing right-side columns with NULL.
SELECT s.sid, s.sname, e.cid
FROM Student AS s
LEFT OUTER JOIN Enrolled AS e
ON s.sid = e.sid;This query includes Ben with a NULL value for cid. A right outer join preserves every row from the right table. A full outer join preserves unmatched rows from both tables, although some database systems do not support it directly.
| Join | Preserves unmatched rows |
|---|---|
| Inner join | Neither side |
| Left outer join | Left side |
| Right outer join | Right side |
| Full outer join | Both sides |
Exam strategy
For a join, first count matching pairs, not distinct entities. One student enrolled in three courses produces three joined rows. Then check whether the query is inner or outer. Finally inspect any WHERE condition: a condition on a nullable outer-joined column can remove the preserved rows and make the query behave like an inner join.
Exercise
If Student has 4 rows and every student has exactly 2 matching Enrolled rows, how many rows does an inner join on sid produce?
Show answer
8 rows. Each of the 4 students forms 2 matching pairs.