Joining Orders to Products in SQL
Some relationships need a middle table before the result has all the details.
One order can contain many products, and one product can appear in many
orders. That many-to-many relationship is stored in the
order_items
bridge table.
To show order details with product names, join
orders
to
order_items, then join
order_items
to
products.
select a.id_column, b.bridge_column, c.detail_column
from table_a as a
join bridge_table as b
on a.id_column = b.id_column
join table_c as c
on b.other_id = c.other_id A bridge is safe because each line item points at one order and one product. Joining two child tables of the same parent isn't: see why a many-to-many join inflates totals. And join on ids, not names: see why joining on names is risky.
Schema · Garden Shop Tables · order_items, orders, products 3 tables
One row per line item within an order.
One row per order. Unshipped orders have a null shipped_date.
One row per product, with price, cost, and inventory levels.
Show the order id, order date, product name, quantity, and calculated line total for orders 1 through 3. Sort by order id, then product name.
Run your query to inspect the result.
Expected answer
- Columns: order_id, order_date, product_name, quantity, line_total.
- Rows: 6 line items for orders 1, 2, and 3.
- Order 1 should include Fiddle-Leaf Fig and Potting Soil 20L.
Related
INNER, LEFT, RIGHT, FULL, and CROSS joins.
Join types and common join patterns.
Practice join keys, left joins, duplicate rows, and debugging.
One-to-many joins can inflate totals.
Qualify shared columns with a table alias.
Nested SELECTs, IN, EXISTS, and correlation.