Write SQL to compute current product stock
Reinforce LabsSoftware Engineer · Online AssessmentLast updated
This problem tests the ability to calculate current stock levels by aggregating historical transaction events against an initial inventory baseline using SQL joins and window functions.
Problem Statement
Given two tables, inventory_baseline and inventory_transactions, calculate the current stock level for every product.
Tables
inventory_baseline (Initial state as of the start of the year):
product_id: INTstock_count: INT
inventory_transactions (All movements since the start of the year):
transaction_id: INTproduct_id: INTchange_amount: INT (Positive for incoming stock, negative for sales)transaction_date: DATETIME
Task
Write a SQL query that returns a list of all product_ids and their current_stock. The current_stock is defined as the sum of the stock_count from the baseline and the total sum of change_amount from all transactions. If a product has no transactions, the baseline value should still be returned.
Examples
Example Input:
inventory_baseline
| product_id | stock_count |
|---|---|
| 1 | 100 |
| 2 | 50 |
inventory_transactions
| product_id | change_amount |
|---|---|
| 1 | -20 |
| 1 | 5 |
| 2 | 10 |
Example Output:
| product_id | current_stock |
|---|---|
| 1 | 85 |
| 2 | 60 |
Constraints
product_idininventory_transactionsmight not exist ininventory_baseline.- A product may have zero transactions.
- Handle NULL values appropriately if a product exists in the baseline but not in the transaction table.
Hints
Hint 1
Consider using a LEFT JOIN to ensure all products from the baseline are included even if they have no corresponding transactions.
Hint 2
Use the COALESCE function to treat NULL transaction sums as zero.
Hint 3
Group the transactions by `product_id` before joining them to the baseline table to optimize performance.
Follow-up questions
- How would you modify your query to return only products where the current stock is below a certain reorder threshold?
- What changes would be required to calculate the stock levels as of a specific historical date?
- If the `inventory_transactions` table grows to billions of rows, how would you optimize this calculation?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.