Combining Tables with Joins
Compare matching rows with an outer join that retains unmatched books.
database, sql, postgresql, joins, relationshipsMatch rows, not just tables
A join combines rows according to a condition. With books on the left and
authors on the right, b.author_id = a.id connects a book to its author.
An inner join returns matching pairs. A left join also retains
unmatched left-side books, filling the right-side columns with NULL.
SQL illustration
First run the fictional setup in Relationships, Constraints, and Normalisation in the same PostgreSQL session. Then compare:
SELECT b.id, b.title, a.name
FROM books AS b
JOIN authors AS a ON b.author_id = a.id
ORDER BY b.id;
Prepared inner-join result:
| id | title | name |
|---|---|---|
| 1 | Kite | Ada |
| 2 | Oak | Ada |
| 3 | Tide | Bo |
SELECT b.id, b.title, a.name
FROM books AS b
LEFT JOIN authors AS a ON b.author_id = a.id
ORDER BY b.id;
Prepared left-join result:
| id | title | name |
|---|---|---|
| 1 | Kite | Ada |
| 2 | Oak | Ada |
| 3 | Tide | Bo |
| 4 | Fern | NULL |
Kite and Oak both match Ada. Fern has no author ID, so only the left join
retains it. Cy has no matching book, and is not retained here because
authors is on the right. To retain all authors, start from authors on
the left. These are prepared results, not live queries.
See the reasoning
Follow the example one step at a time
Compare matching pairs with a left join that keeps unmatched books. This is a prepared teaching demonstration, not live code execution.
Compare the keys
book author_id author Kite 1 ─────→ 1 Ada Oak 1 ─────→ 1 Ada Tide 2 ─────→ 2 Bo Fern NULL no match
The condition compares each book's author_id to an author ID. Fern has no matching author.
Conditions matter
One-to-many matches can increase result rows; a join is not automatically
one row per author. A missing or incorrect join condition can produce many
unintended combinations. RIGHT JOIN preserves the right side, and FULL OUTER JOIN preserves unmatched rows from both sides. A later WHERE filter
on a right-side column can remove the NULL-extended rows from a left join;
decide whether a condition belongs in ON or WHERE for the intended result.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
