Reading preferences
Concept

Combining Tables with Joins

Compare matching rows with an outer join that retains unmatched books.

database, sql, postgresql, joins, relationships

Match 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:

idtitlename
1KiteAda
2OakAda
3TideBo
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:

idtitlename
1KiteAda
2OakAda
3TideBo
4FernNULL

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.

1. What does the inner join return for Fern?
2. What does the left join do with Fern?
3. Can a join produce multiple rows for one author?
4. Why can WHERE a.name = 'Ada' remove unmatched rows after a left join?

References and further reading