Sub topic 9
Rolling Up a Bill of Materials
A bill of materials (BOM) lists the parts needed to build an item. An assembly can contain parts that are themselves assemblies. A recursive common table expression (CTE) can expand this structure and calculate the total quantity of every component.
This chapter assumes you know SELECT, joins, GROUP BY, aggregate functions, and basic subqueries.
The BOM table
Assume a table named bom with one row for each assembly-component relationship:
| assembly_id | component_id | qty |
|---|---|---|
| 100 | 200 | 2 |
| 100 | 400 | 1 |
| 200 | 300 | 3 |
This means:
- Assembly
100needs two units of assembly200. - Assembly
100also needs one unit of component400. - Each unit of assembly
200needs three units of component300.
Therefore, one unit of assembly 100 needs six units of component 300: 2 × 3.
Expand each level
The anchor member finds the direct components of the top-level assembly. The recursive member finds components inside those components.
WITH RECURSIVE exploded AS (
SELECT
component_id,
qty,
1 AS depth
FROM bom
WHERE assembly_id = 100
UNION ALL
SELECT
b.component_id,
e.qty * b.qty AS qty,
e.depth + 1 AS depth
FROM exploded AS e
JOIN bom AS b
ON b.assembly_id = e.component_id
WHERE e.depth < 50
)
SELECT
component_id,
SUM(qty) AS total_qty
FROM exploded
GROUP BY component_id
ORDER BY component_id;The qty column stores the quantity required along the current path. When the query moves down one level, it multiplies the existing quantity by the child quantity.
For the sample data, the recursive rows include:
- Component
200, quantity2 - Component
400, quantity1 - Component
300, quantity6
The final SUM combines rows when the same component appears in several branches. This matters when a component is used by multiple sub-assemblies.
Choosing the output
The query above returns assemblies as well as lower-level parts. If you need only purchasable parts, add a table that identifies which components are assemblies, or use a NOT EXISTS condition:
SELECT
e.component_id,
SUM(e.qty) AS total_qty
FROM exploded AS e
WHERE NOT EXISTS (
SELECT 1
FROM bom AS child
WHERE child.assembly_id = e.component_id
)
GROUP BY e.component_id;This treats a component as a leaf when it never appears as an assembly_id.
Quantity and duplicate paths
Use UNION ALL for BOM expansion. Two different paths may legitimately reach the same component, and both paths contribute to the required quantity. Using UNION removes duplicate rows and can produce an incorrect total.
A depth limit also protects the query from unexpectedly deep data. Choose a limit larger than the deepest valid product structure, then monitor rows that reach that limit.
Exercise
Assembly 500 uses four units of assembly 600. Assembly 600 uses five units of part 700. How many units of part 700 are required for assembly 500?
Show answer
Twenty units, because the recursive quantity is multiplied at each level: 4 × 5 = 20.