Intermediate Case 34 of 50

Case 034: At-Risk Stock

productsinventoryorder_items

Operations is worried about running out of popular items, and the manager passes the concern to Alex.

"Could you show me everything under 20 units in stock, and how much of it has actually been selling?"

The data Alex is looking at

products
idnamecategoryprice
1KeyboardAccessories2500
2MouseAccessories1200
3HeadphonesAudio3500
4MonitorDisplays12000
5LaptopComputers60000
… 5 more rows
inventory
product_idstock
140
225
360
415
520
… 5 more rows
order_items
order_idproduct_idquantity
10112
10121
10231
10323
10451
… 29 more rows
TASK

Help Alex answer the manager:

“For every product with fewer than 20 units in stock, show its stock level and how many units have sold so far, most in-demand first.”
SQL editor Ctrl+Enter to run
Write a query above and hit Run to see what comes back.
No hints requested yet — click "Get a hint" when you're stuck.
Alex's final query — this is for reference. Copy it into your own thinking, not into the editor above.
SELECT products.name, inventory.stock, COALESCE(SUM(order_items.quantity), 0) AS units_sold FROM products JOIN inventory ON inventory.product_id = products.id LEFT JOIN order_items ON order_items.product_id = products.id WHERE inventory.stock < 20 GROUP BY products.name, inventory.stock ORDER BY units_sold DESC;
What that query returns
Case Debrief LEFT JOIN + COALESCE
  • LEFT JOIN + COALESCE is the standard combination for "keep everything, even with no activity, and show 0 instead of NULL" business reports.

Case closed.

Ready for the next one?

Next: Case 035 — The Churn Signal →