← Back to SQL, page 15

sql-0285 · Hard senior

A bill of materials says a bike has 2 wheels and each wheel has 32 spokes. Write a recursive query for the total number of each part needed for one bike.

Start from the top assembly with quantity 1, then join each part to its components and multiply the quantity on the path by the component quantity. Sum the results per part at the end, because the same part can appear under several assemblies.

Full answer
sql
WITH RECURSIVE bom(parent, part, qty) AS (VALUES
  ('bike', 'wheel', 2), ('bike', 'frame', 1), ('wheel', 'spoke', 32), ('wheel', 'hub', 1),
  ('wheel', 'bolt', 2), ('frame', 'bolt', 4)),
 need(part, qty) AS (
  SELECT 'bike', 1
  UNION ALL
  SELECT b.part, n.qty * b.qty FROM need n JOIN bom b ON b.parent = n.part
)
SELECT part, SUM(qty) AS total FROM need WHERE part <> 'bike' GROUP BY part ORDER BY part;
parttotal
bolt8
frame1
hub2
spoke64
wheel2

The recursion carries the cumulative quantity down the tree: 1 bike, 2 wheels, 2 × 32 = 64 spokes, 2 × 1 = 2 hubs. The frame's 4 bolts and the wheels' bolts (2 × 2 = 4) are added together in the final GROUP BY, giving 8.

Without the final SUM, a part that appears in several branches shows up as several rows. The same pattern answers "total cost of a product" if each leaf carries a unit price: multiply the quantity by the price and sum.

sql
WITH RECURSIVE bom(parent, part, qty) AS (VALUES
  ('bike', 'wheel', 2), ('bike', 'frame', 1), ('wheel', 'spoke', 32), ('wheel', 'hub', 1),
  ('wheel', 'bolt', 2), ('frame', 'bolt', 4)),
 need(part, qty) AS (
  SELECT 'bike', 1
  UNION ALL
  SELECT b.part, n.qty * b.qty FROM need n JOIN bom b ON b.parent = n.part
)
SELECT part, SUM(qty) AS total FROM need WHERE part <> 'bike' GROUP BY part ORDER BY part;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Seed the recursion with the top item and quantity 1
  • Multiply quantities along each path
  • Sum per part at the end
  • The same part can appear in several branches

Common mistakes

  • Adding quantities instead of multiplying them
  • Forgetting the final aggregation

Follow-ups

  • How would you compute the cost of one bike?
  • How would you detect a cycle in the parts data?

Tips

  • Walk through the multiplication for spokes