SQL INNER JOIN: Combine Rows From Two Tables
The books table does not store author names. It stores author_id, a number that points at a row in authors. That design avoids repeating the same name on many rows and keeps every fact in one place. To see titles and names together, you join the two tables.
Foreign keys
books.author_id is a foreign key: its values are ids from another table. "Learning SQL by Doing" has author_id 4, and the author with id 4 is Tom Becker. A join follows that link for every row.
INNER JOIN ... ON
FROM books AS b JOIN authors AS a ON a.id = b.author_id pairs each book with the author whose id equals the book's author_id. JOIN on its own means INNER JOIN: only pairs that match appear in the result. A book with no matching author, or an author with no books, is left out.
b and a are table aliases. They keep queries short and make it clear which table each column comes from, which is required when both tables have a column with the same name, like id or name. The word AS is optional for table aliases, as the second query shows.
Expected output
title | author | country Learning SQL by Doing | Tom Becker | USA Northern Lights Code | Maya Lindqvist | Sweden Small Data, Big Ideas | Tom Becker | USA name | order_id | ordered_on Liam Chen | 2 | 2025-09-03 Emma Rossi | 6 | 2025-10-21 Liam Chen | 7 | 2025-11-05
Filtering, sorting and selecting
After the join, the query works with the combined rows as if they were one wide table. WHERE b.genre = 'Tech' filters, ORDER BY b.title sorts, and the SELECT list can take columns from either side. The second query joins orders to customers to list orders placed by customers in Austin, in date order.
Joining more tables
Joins can be chained. To list which books each customer bought, join customers to orders, orders to order_items, and order_items to books, each with its own ON condition. Write one JOIN per line so the chain stays readable.
Join conditions matter
Leaving out the ON condition, or writing it wrong, pairs every row of one table with every row of the other: 10 books times 5 authors gives 50 meaningless rows. If a join returns far more rows than you expect, check the ON clause first.
Common mistakes
- Ambiguous column names:
SELECT namewhen both tables havename. Prefix with the alias. - Joining on the wrong columns, for example
a.id = b.idinstead ofa.id = b.author_id. - Expecting rows without a match to appear; that requires a
LEFT JOIN, covered next.
Summary
- Foreign keys link rows across tables; joins follow those links.
JOIN ... ON(inner join) returns only matching pairs.- Use table aliases and prefix columns with them.
- A missing or wrong
ONcondition multiplies rows.
Quiz: INNER JOIN