Scenario: Brightlane's operations team wants a complexity metric for each order — the count of line items it contains.
Task: Write a query to return each order's id and the number of line items it contains.
Assumptions:
- The result covers only
orderswith at least one line item on record.
Output:
- One row per order with at least one line item.
- Columns in this order:
order_id,item_count.
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
o.id AS order_id,
COUNT(oi.id) AS item_count
FROM
orders o
JOIN order_items oi ON oi.order_id = o.id
GROUP BY
o.id The shape
COUNT(oi.id) on the joined result counts one row per line item per order, which is exactly what the complexity metric is — line items per order. Grouping by o.id then collapses those rows into one count per order.
Clause by clause
SELECT o.id AS order_id, COUNT(oi.id) AS item_countreturns each order's ID and the count of its line items.COUNT(oi.id)counts non-nulloi.idvalues inside each group, which equals the number of line items the order has.FROM orders oreads the order records as the driving table.JOIN order_items oi ON oi.order_id = o.idpairs each order with its line items. The inner join drops any order with zero line items, which matches the prompt's "covers only orders with at least one line item" constraint.GROUP BY o.idcollapses the multi-row-per-order joined result into one row per order, with the count computed inside each group.
Why this and not COUNT(*)
On an inner join with a guaranteed match on every line item, COUNT(*) and COUNT(oi.id) produce the same result here. The habit of counting a specific child-table column matters more on a LEFT JOIN, where a parent with zero line items still appears in the result with NULLs on the child side — COUNT(*) would count that row as one, but COUNT(oi.id) correctly returns zero. Writing COUNT(oi.id) even on the inner-join version keeps the pattern consistent and the intent explicit.
You practiced totaling child-row counts up to the parent — one line per order with the count of its associated line items.