Calculate Current Item Inventory from Movements and Baselines
SQL & DataModel answerLast updated
Compute up-to-date item stock by merging starting snapshot balances with subsequent movement logs using SQL aggregations and joins.
You are managing an inventory system that tracks product stock movements over time. You have a starting inventory snapshot from the beginning of the period and a streaming ledger of all adjustments (such as shipments, returns, and sales) recorded since that snapshot.
Write an ANSI SQL query to compute the current overall stock for every item present in the baseline inventory dataset.
Schema Details
-
inventory_baseline(Initial balance per product):product_id(INT): Unique identifier for the item.stock_count(INT): The quantity recorded at the starting point.
-
inventory_transactions(Subsequent movement log):transaction_id(INT): Primary key of the movement record.product_id(INT): Identifier of the item moved.change_amount(INT): Adjustment quantity (positive values denote added stock; negative values denote dispatched stock).transaction_date(DATETIME): Timestamp of the event.
Target Output
Your query should yield a record set containing:
product_idcurrent_stock: The initial baseline stock plus the sum total of all valid changes recorded for that item.
Rules & Edge Cases
- Include every
product_idlisted ininventory_baseline. - If an item in
inventory_baselinehas no entries ininventory_transactions, its outputcurrent_stockmust equal its baseline quantity. - Transactions might reference a
product_idnot present ininventory_baseline; these non-baseline items should be omitted unless specified otherwise. - Aggregate operations must correctly treat missing movement totals as zero rather than
NULL.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Architecture
To derive the current inventory state for every catalog item, we combine the initial baseline quantity with the net ledger adjustments:
$$\text{current_stock} = \text{baseline.stock_count} + \sum(\text{transactions.change_amount})$$
A naive join between inventory_baseline and inventory_transactions before aggregation causes a fan-out problem: if a product has $N$ transactions, its baseline row is duplicated $N$ times. Computing SUM(stock_count) across that joined set will inflate the initial balance by a factor of $N$.
The optimal pattern follows three clean steps:
- Pre-aggregate movements: Group the
inventory_transactionstable byproduct_idin a Common Table Expression (CTE) to calculate the net modificationnet_changeper product. - Left Join: Perform a
LEFT JOINfrominventory_baselineto the aggregated CTE onproduct_id. This guarantees all baseline items remain in the result set regardless of activity. - Handle missing values: Utilize
COALESCE(t.net_change, 0)to handle products with no transaction events, preventing standardNULLaddition propagation (100 + NULL = NULL).
Solution (SQL)
WITH product_deltas AS (
SELECT
product_id,
SUM(change_amount) AS net_change
FROM inventory_transactions
GROUP BY product_id
)
SELECT
b.product_id,
b.stock_count + COALESCE(d.net_change, 0) AS current_stock
FROM inventory_baseline AS b
LEFT JOIN product_deltas AS d
ON b.product_id = d.product_id
ORDER BY b.product_id;
Key Requirements & Corner Cases
- One-to-One / One-to-Zero Join: Because aggregation takes place inside the
product_deltasCTE first, eachproduct_idappears at most once inproduct_deltas. Joining to a unique baseline primary key avoids row duplication entirely. - Missing Transactions: Products present in
inventory_baselinebut absent frominventory_transactionsoutputd.net_changeasNULL.COALESCEconverts this to0, producingb.stock_count + 0. - Orphan Transactions: Transactions referencing unknown
product_ids not present ininventory_baselineare filtered out by theLEFT JOIN. If requirements dictate including orphan items with an implied zero baseline, aFULL OUTER JOINcan be used:
-- Alternative for handling non-baseline products
WITH product_deltas AS (
SELECT
product_id,
SUM(change_amount) AS net_change
FROM inventory_transactions
GROUP BY product_id
)
SELECT
COALESCE(b.product_id, d.product_id) AS product_id,
COALESCE(b.stock_count, 0) + COALESCE(d.net_change, 0) AS current_stock
FROM inventory_baseline AS b
FULL OUTER JOIN product_deltas AS d
ON b.product_id = d.product_id;
Complexity Analysis
- Time Complexity: $\mathcal{O}(T + B)$ where $T$ is the number of transaction rows and $B$ is the number of baseline rows. Aggregate hash grouping takes $\mathcal{O}(T)$ time, and the hash join takes $\mathcal{O}(B + U)$ where $U \le T$ is the count of distinct products in transactions. Adding
ORDER BYappends an $\mathcal{O}(B \log B)$ sorting pass. - Space Complexity: $\mathcal{O}(U)$ space needed to hold the pre-aggregated CTE key-value pairs in memory.
Common Follow-Up Questions
1. How would you filter for items falling below a specific reorder limit?
Wrap the base aggregation in a CTE or outer query, or append a WHERE clause explicitly restating the addition formula (since column aliases cannot be referenced in standard SQL WHERE clauses):
SELECT
b.product_id,
b.stock_count + COALESCE(d.net_change, 0) AS current_stock
FROM inventory_baseline AS b
LEFT JOIN product_deltas AS d ON b.product_id = d.product_id
WHERE b.stock_count + COALESCE(d.net_change, 0) < 15;
2. How do you process historical stock levels for a given cutoff date?
Filter the transactions within the CTE using a half-open time boundary to capture all records up to midnight of the target date:
WITH product_deltas AS (
SELECT
product_id,
SUM(change_amount) AS net_change
FROM inventory_transactions
WHERE transaction_date < '2024-04-01 00:00:00'
GROUP BY product_id
)
...
3. How do you scale this for high-throughput tables containing billions of transactions?
- Covering Index: Place a composite index on
inventory_transactions(product_id, change_amount)to allow index-only aggregation scans without reading table heaps. - Periodic Snapshotting: Run a daily job that writes updated daily closing balances to a
daily_inventory_snapshottable. Queries then aggregate only the small volume of transactions occurring after the latest daily snapshot.