Start learning free

LESSON 58 OF 173 · BACKEND: SQL

Join Three Tables

Practice

One JOIN connects two tables. A query can have as many JOINs as it needs, one after another, and each one brings in a table with its own ON rule.

You need this for a table that links two others by their ids. In the shop, order_items has one row per product in an order: its order_id, its product_id and the quantity. It holds no date and no product name: the date is in orders, the name in products.

For example, a school's enrollments table links students to courses, and this query names both sides of each enrollment:

SELECT students.name, courses.title
FROM enrollments
JOIN students
ON enrollments.student_id = students.id
JOIN courses
ON enrollments.course_id = courses.id

Your query shows what each order contains: the order's id and date, the product's name and the quantity, one row per item. In your code, each clause is one string in the query array. The check prints:

id | ordered | name | quantity
1 | 2026-03-02 | Mug | 2
1 | 2026-03-02 | Pen | 5
2 | 2026-03-15 | Lamp | 1
3 | 2026-04-05 | Notebook | 3
3 | 2026-04-05 | Pen | 10
4 | 2026-04-18 | Plant | 1
4 | 2026-04-18 | Mug | 1
5 | 2026-05-07 | Teapot | 2
5 | 2026-05-07 | Lamp | 1
6 | 2026-05-21 | Stapler | 1
7 | 2026-05-30 | Mug | 4
7 | 2026-05-30 | Notebook | 2
(12 rows)

Your task: select orders.id, orders.ordered, products.name and order_items.quantity from order_items, then join orders and products, each with its own ON.


Assignment
Follow the Coding Tutorial to start from order_items and join orders, then products, each JOIN with its own ON string.


Hint
Each ON compares a column of order_items with the id of the table being joined: order_id goes with the orders, product_id with the products.


STEP 1 OF 4
    Ctrl + Enter to check