Brightlane's fulfilment team needs a manifest of all order line items, showing the product name, quantity, and unit price for each line.
Write a query to return one row per order line item with the matching product name plus the line's quantity and unit price.
Assumptions:
- The
order_itemstable contains one row per product per order;product_idon each line points to a row inproducts. - The
productstable contains every product in the catalogue, identified byproducts.id. - Every line item has a valid
product_id.
Output:
- One row per order line item, with columns
product_name,quantity, andunit_price.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
p.name AS product_name,
oi.quantity,
oi.unit_price
FROM
order_items oi
JOIN products p ON oi.product_id = p.id The shape
Each row in order_items represents one product on one order, and the line carries a product_id reference but not the product's name. Joining to products on that reference attaches the catalogue name to every line, so the fulfilment manifest reads as Men's Slim Jeans, 1, 59.99 instead of 42, 1, 59.99.
Clause by clause
FROM order_items oireads from the line-items table and aliases it asoi. Every row here is one product on one order, withquantityandunit_pricerecorded at the time of purchase andproduct_idas the link back to the catalogue.JOIN products p ON oi.product_id = p.idpairs each line with its product. For every row inorder_items, PostgreSQL finds the row inproductswhoseidequals that line'sproduct_id, and emits a combined row holding both sides. Because every line has a validproduct_id, every line item appears in the result.SELECT p.name AS product_name, oi.quantity, oi.unit_pricepicks the product name from the catalogue side and the per-line quantity and unit price from the line itself. The qualifier onp.nameis structural. Both tables carry anidcolumn, and writingoi.product_id = id(without thep.) would be ambiguous. Once the aliases are in place, every column reference reads cleanly:p.nameis from products,oi.quantityandoi.unit_priceare from the line.
You practiced joining a junction-style fact table (order_items) to one of its parent dimensions (products). The recurring shape: junction tables almost always join to multiple parents; this problem joins to one of them, and joining to the customer/order side later follows the same pattern.