Join Order Items to Products to Show Product Names
Return every order line together with the name of the product it refers to.
The challenge runs on the SQLabHub practice database (SQLite) and uses the products and order_items tables. You can solve it in the browser, with nothing to install.
The task
Get order_items along with product name.
A correct answer returns 496 rows with 7 columns: id, order_id, product_id, quantity, unit_price, subtotal, name.
Tables used in this challenge
products 120 rows
id INTEGER (PK) · name TEXT · category TEXT · price REAL · cost REAL · stock INTEGER · sku TEXT · status TEXT · rating REAL · review_count INTEGER
| id | name | category | price | cost | stock | sku | status | rating | review_count |
|---|---|---|---|---|---|---|---|---|---|
order_items 496 rows
id INTEGER (PK) · order_id INTEGER · product_id INTEGER · quantity INTEGER · unit_price REAL · subtotal REAL
| id | order_id | product_id | quantity | unit_price | subtotal |
|---|---|---|---|---|---|
The first rows of each table are shown. See how all the tables relate on the database schema page.
Expected output
| id | order_id | product_id | quantity | unit_price | subtotal | name |
|---|---|---|---|---|---|---|
First 5 of 496 rows. This is the output of the model solution on the practice database. The task does not fix a sort order, so your rows may come back in a different order.
What you practise
- Combining rows from two tables on a matching key with an inner join
Hint and approach
Try the challenge first. Open these only when you need them.
Show the hint
JOIN order_items and products
Show the step-by-step approach
How the model solution is built, in the order the database evaluates it:
- Read from the
order_itemstable. - Join
productsonorder_items.product_id=products.id.
Model solution
Checking your session…
What to watch for
order_items.product_id points at products.id. An inner join returns a line only when its product exists; here every line has one, so the row count equals the number of order lines.
- INNER JOIN. An inner join drops rows that have no partner on the other side, and it repeats a row once for every match, which inflates SUM and COUNT.
Related SQL challenges
- Calculate the Average Review Rating per Product CategorySimilar levelMedium
- Join Three Tables: Orders, Users and PaymentsSimilar levelMedium
- Calculate Profit Generated by Each CustomerHarderHard
- Find Orders Whose Payment Amount Differs from the Order TotalSimilar levelMedium
- Calculate Average Items per Order for Each CustomerHarderHard
Same technique, other tables
More practice on this pattern with different columns:
Keep learning
- Lesson: INNER JOIN
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database