DSA Factory
Free SQL queries lessonsSQL queries · Stage 3 · Joining tables · Step 1

Bring two tables together

Combine rows of two tables that belong together with JOIN and ON. About 9 minutes.

Each fact lives in one place

The library keeps books in one table and authors in another. A book row holds an author_id, a number that points at a row of authors. The author's name is written once, in authors, not copied onto every book.

That keeps the data tidy, but a question like "each title with its author's name" needs both tables. JOIN brings them together.

author_id: points at the matching row of authors.

JOIN … ON pairs up matching rows

After FROM name the first table, then JOIN the second and say how rows match with ON. Each row of the first table is paired with the rows of the second where the test is true.

Give each table a short alias, like b and a, and put it before the column (b.title). It is needed when both tables have a column of the same name, such as id. A row with no partner on the other side isn't in the answer.

No ON: pairs every row with every row. Never skip it.
In code
SELECT b.title, a.name
FROM books b
JOIN authors a ON a.id = b.author_id;
Each book with its author
books
idtitleauthor_id
1Godaan10
2Gitanjali11
3The Guide12
authors
idname
10Premchand
11Tagore
12R. K. Narayan

Take the first book. Its author_id is 10.

Move 1 of 6
Quick check

What does ON a.id = b.author_id do?

  1. AIt says which row of authors belongs to each row of books
  2. BIt keeps only the books written by author 1
  3. CIt sorts the books by author
Show the answer

It says which row of authors belongs to each row of books. ON is the matching rule that decides which rows get paired.

Your problem

Who teaches what

The courses table has one row per course and the id of its teacher, and teachers has one row per teacher. Show each course's title and its teacher's name as teacher. Order by title.

Tables
teachers(id, name)
courses(id, title, teacher_id)

Up to 1,000 courses · course titles are unique

Write the query in your browserFree account, no card. Your query runs on real tables, with hints if you get stuck, and your progress is saved.
Sign up free to solve