An Inner Join Drops Rows Without a Match, a Left Join Keeps Them
An inner join returns only rows that have a match on both sides; a left (outer) join returns every row of the left table, with NULLs where the right side has no match. Choosing the wrong one doesn't raise an error: the query silently loses rows (authors without books vanish from a report) or keeps rows you meant to exclude. Rails makes the choice explicit with joins and left_joins.
The Same Question, Two Answers
Author.joins(:books) # INNER JOIN: only authors with at least one book
Author.left_joins(:books) # LEFT OUTER JOIN: every author, books or not
| Author | Books | In joins |
In left_joins |
|---|---|---|---|
| Ada | 2 | yes (twice: once per book) | yes (twice) |
| Grace | 0 | no | yes (book columns NULL) |
Use joins when every row of the main table must have a related row, or when you want only those that do. Use left_joins when the main table's rows must all appear, related or not.
Two Common Patterns
# authors with no books: left join, then keep the NULLs
Author.left_joins(:books).where(books: { id: nil })
# count books per author, including zero
Author.left_joins(:books).group(:id).count("books.id")
Django's ORM picks the join type for you: it uses an inner join for a required foreign key and a left outer join when the relation can be NULL, or when you filter "is null" across a relation.
References
- Programming Languages MOC - hub for language and database notes.
- PostgreSQL Cheat Sheet - running and inspecting these queries in psql.
- Rails Guides: Active Record Query Interface, joining tables -
joinsandleft_outer_joins. - PostgreSQL documentation: Joins Between Tables - inner and outer joins.
Review cards
Flashcard Why does `Author.joins(:books)` leave out some authors?
It's an inner join: it returns only rows with a match on both sides, so authors without books vanish, silently, with no error.
Flashcard Why does `left_joins(:books).where(books: { published: true })` drop authors without books?
Their book columns are NULL, so the WHERE condition fails and the left join behaves like an inner one. Put the condition in the join, or use a subquery.
Quiz Which query returns only the authors with no books?
-
Author.left_joins(:books).where(books: { id: nil }) -
Author.joins(:books).where(books: { id: nil }) -
Author.left_joins(:books) -
Author.left_joins(:books).where(books: { published: true })
The left join keeps every author, with NULL book columns for those without books; keeping the NULL ids selects exactly them. An inner join has no such rows to find.