Interview Questions/SQL/Bill of Materials - Recursive Cost Explosion

Bill of Materials - Recursive Cost Explosion

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a product Components table and a BOM (Bill of Materials) table. Each product can have sub-components, each of which may itself have sub-components (multi-level). Write a SQL query to find the total material cost for each component that appears as a parent, by recursively exploding all nested sub-components and multiplying quantities. Return (root_id, product_name, total_cost) ordered by root_id. Table: Components

Column NameTypeDescription
component_idINTPrimary key
nameVARCHARComponent name
unit_costREALCost per unit (0 if it is an assembly)

Table: BOM

Column NameTypeDescription
parent_idINTParent component id
child_idINTChild component id
quantityINTNumber of child units needed per parent unit

Database Schema (Inferred)

Components

Column NameExample Value
component_id1
nameBike
unit_cost0

BOM

Column NameExample Value
parent_id1
child_id2
quantity1

Example

Components

component_idnameunit_cost
1Bike0
2Frame100
3Wheel0
4Rim30
5Tire20
6Handlebar15

BOM

parent_idchild_idquantity
121
132
161
341
351

Output

root_idproduct_nametotal_cost
1Bike215
3Wheel50

Explanation:

Bike = 1×Frame(100) + 2×Wheel(Rim30+Tire20=50 each → 100) + 1×Handlebar(15) = 215. Wheel = Rim(30)+Tire(20) = 50. The explosion multiplies quantities at every level.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Components

component_idnameunit_cost
1Bike0
2Frame100
3Wheel0
4Rim30
5Tire20
6Handlebar15

BOM

parent_idchild_idquantity
121
132
161
341
351

Output

root_idproduct_nametotal_cost
1Bike215
3Wheel50