Sub topic 9
Rolling up a bill of materials
This chapter assumes you can write self-joins, use GROUP BY with aggregates, and read a basic WITH RECURSIVE query (an anchor member, a recursive member, and UNION ALL). If the working table is unfamiliar, review the chapter on how the database evaluates a recursive CTE first.
What a bill of materials is
A bill of materials (BOM) lists what a product is made of. A bike has a frame and wheels. A frame has tubes and bolts. A wheel has bolts and spokes. Each link says "this assembly uses N of that component." The same component can show up under several assemblies, at several depths.
A BOM is stored as a table of edges, one row per link:
CREATE TABLE bom (
assembly_id INTEGER NOT NULL,
component_id INTEGER NOT NULL,
qty INTEGER NOT NULL
);
CREATE TABLE parts (
part_id INTEGER PRIMARY KEY,
unit_cost NUMERIC(10,2) NOT NULL
);
INSERT INTO bom (assembly_id, component_id, qty) VALUES
(100, 200, 1), -- bike uses 1 frame
(100, 300, 2), -- bike uses 2 wheels
(200, 500, 3), -- frame uses 3 tubes
(200, 600, 4), -- frame uses 4 bolts
(300, 600, 5), -- wheel uses 5 bolts
(300, 700, 32); -- wheel uses 32 spokes
INSERT INTO parts (part_id, unit_cost) VALUES
(500, 2.00), (600, 0.10), (700, 0.05);The question a manufacturer asks is: how many of each part do I need to build one bike? Bolts appear under both the frame and the wheels, so no single join answers it.
Explode, then aggregate
A BOM rollup has two phases:
- Explosion. A recursive CTE walks down from the top assembly and produces one row for every use of every component, with a quantity that already accounts for the levels above it.
- Rollup. The outer query groups those rows by component and sums the quantities.
Here is the explosion and rollup together:
WITH RECURSIVE exploded AS (
SELECT component_id, qty
FROM bom
WHERE assembly_id = 100
UNION ALL
SELECT b.component_id, x.qty * b.qty
FROM exploded x
JOIN bom b ON b.assembly_id = x.component_id
)
SELECT component_id, SUM(qty) AS total_qty
FROM exploded
GROUP BY component_id;The anchor member selects the direct children of assembly 100. Each recursive step joins the rows found in the previous iteration to their own children. The key expression is x.qty * b.qty. It multiplies the quantity accumulated so far by the quantity on the new link.
Here is what exploded holds before the outer query groups it:
| component_id | qty | How it was computed |
|---|---|---|
| 200 | 1 | direct child of the bike |
| 300 | 2 | direct child of the bike |
| 500 | 3 | 1 frame × 3 tubes |
| 600 | 4 | 1 frame × 4 bolts |
| 600 | 10 | 2 wheels × 5 bolts |
| 700 | 64 | 2 wheels × 32 spokes |
Bolt 600 appears twice, once per path. The outer SUM turns those into 14. The final result is 200 → 1, 300 → 2, 500 → 3, 600 → 14, 700 → 64.
The multiplication happens inside the recursion because the quantity at each level depends on the path taken to reach it. Summing first and multiplying later would give wrong numbers.
Why aggregation stays outside the recursion
You cannot put SUM or GROUP BY in the recursive member in most databases. PostgreSQL, SQL Server, and MySQL all reject aggregate functions that reference the recursive CTE there. The explode-then-aggregate pattern is the standard workaround: the recursion produces raw path rows, and the outer query collapses them.
This also explains the volume. The explosion produces one row per path, not per distinct component. A part used in many sub-assemblies produces many rows. That is usually fine, but it matters for performance, as covered below.
Keeping only the purchasable parts
The result above mixes assemblies (200, 300) with raw parts (500, 600, 700). Purchasing usually wants only the leaves: components that are not themselves assemblies. A leaf is a component that never appears in assembly_id.
WITH RECURSIVE exploded AS (
SELECT component_id, qty
FROM bom
WHERE assembly_id = 100
UNION ALL
SELECT b.component_id, x.qty * b.qty
FROM exploded x
JOIN bom b ON b.assembly_id = x.component_id
)
SELECT x.component_id, SUM(x.qty) AS total_qty
FROM exploded x
WHERE NOT EXISTS (
SELECT 1 FROM bom c WHERE c.assembly_id = x.component_id
)
GROUP BY x.component_id
ORDER BY x.component_id;This returns 500 → 3, 600 → 14, 700 → 64. The filter belongs in the outer query. If you put it in the recursive member, you would stop the recursion at the leaves, which is harmless here. You would also lose the intermediate assemblies if you later want them in the same result.
Rolling up cost
Once you have leaf quantities, a cost rollup is a join to parts:
WITH RECURSIVE exploded AS (
SELECT component_id, qty
FROM bom
WHERE assembly_id = 100
UNION ALL
SELECT b.component_id, x.qty * b.qty
FROM exploded x
JOIN bom b ON b.assembly_id = x.component_id
)
SELECT SUM(x.qty * p.unit_cost) AS bike_cost
FROM exploded x
JOIN parts p ON p.part_id = x.component_id;The inner join to parts drops assemblies 200 and 300 because they have no price row. That is correct here: their cost is the cost of their parts, and counting both would double-count. The result is 3 × 2.00 + 14 × 0.10 + 64 × 0.05 = 10.60.
If assemblies carry their own cost, such as labor, you need a different rule, because the join no longer filters them out. Decide explicitly which rows carry a price and filter on that.
Tracking the level
Adding a level counter costs one column and is often worth it. It lets you report quantities per level, and it gives you a safety net against bad data.
WITH RECURSIVE exploded AS (
SELECT component_id, qty, 1 AS level
FROM bom
WHERE assembly_id = 100
UNION ALL
SELECT b.component_id, x.qty * b.qty, x.level + 1
FROM exploded x
JOIN bom b ON b.assembly_id = x.component_id
WHERE x.level < 20
)
SELECT level, component_id, SUM(qty) AS total_qty
FROM exploded
GROUP BY level, component_id
ORDER BY level, component_id;The WHERE x.level < 20 guard caps the depth. A real BOM should have no cycles, since a part cannot contain itself, but data entry mistakes happen. A cap turns an endless loop into a bounded one. The cap also hides the error silently, so a count check on the results is worth adding.
Gotchas
Use UNION ALL, not UNION
The explosion relies on duplicate rows. If two different paths both yield (600, 4), UNION would discard one of them and your total would come out too low. UNION deduplicates whole rows, not paths, so it removes legitimate repeats.
Mind the data types
Multiplied quantities grow fast. Deep BOMs with large per-level quantities can overflow a 32-bit integer. Use BIGINT for qty if your hierarchy is deep or your multipliers are large. For fractional quantities, such as 0.25 kg of resin, use NUMERIC, not a floating-point type, so that sums are exact.
Check the recursion limit
SQL Server stops at 100 recursion levels by default and needs OPTION (MAXRECURSION n) for deeper trees. SQL Server also omits the RECURSIVE keyword. Other dialects set their own limits. Check the dialect chapter if your BOM is deep.
Watch for shared sub-assemblies
If the same sub-assembly is used in many places, the explosion repeats its entire subtree for each use. A frame used in 50 bike models costs 50 times the work if you explode all models at once. Start from one top-level assembly at a time when you can, or filter the anchor with a WHERE on the assembly you need.
Performance notes
The recursive member joins exploded to bom on assembly_id once per iteration. Without an index, each iteration scans all of bom.
CREATE INDEX bom_assembly_idx ON bom (assembly_id, component_id);With this index, each lookup finds a parent's children directly. The explosion row count is the real cost driver: the query does work proportional to the number of paths, not the number of distinct parts. If you roll up the same BOM repeatedly, consider storing the exploded result in a table and refreshing it when the BOM changes.
Exercise
A new row is added to bom: (300, 700, 32) is duplicated by accident, so the wheel now lists spokes twice with 32 each. The rollup query uses UNION ALL. How many spokes (component 700) does the query report for one bike, and what would a UNION version report?
Show answer
With UNION ALL, the wheel produces two spoke rows, each 2 × 32 = 64, so the total is 128 spokes. With UNION, the two identical rows (700, 64) would collapse into one and the total would be 64. The second answer is wrong only because of the duplicate input, but it shows that UNION hides repeated rows, so you could not tell a real double-use from bad data. The fix for the data is a unique constraint on (assembly_id, component_id).
Exercise
Change the explosion query so it reports how many distinct assemblies (not parts) are used to build one bike, counting each assembly type once. Which clause do you change, and which table do you test against?
Show answer
Keep the recursive CTE as is. In the outer query, keep only rows whose component_id appears as an assembly_id in bom, using WHERE EXISTS (SELECT 1 FROM bom c WHERE c.assembly_id = x.component_id), and then use COUNT(DISTINCT x.component_id). For the example data this returns 2 (frame 200 and wheel 300). The test is against bom itself, because an assembly is any component that has children there.