Compute Net Product Stock from Inventory Tables
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Problem Statement
A warehouse system tracks starting quantities in inventory_baseline and records subsequent inbound restocks and outbound fulfillments in inventory_transactions.
Write a SQL query that computes the net on-hand balance for every distinct product_id appearing in either table, returning two columns:
product_id— the SKU's integer identifier.current_stock— an integer equal to that SKU's total startingstock_countininventory_baselineplus the net sum ofchange_amountacross all matching rows ininventory_transactions.
Apply these coverage and null-safety rules:
- Any SKU present in
inventory_baselinewith zero rows ininventory_transactionsretains its starting balance. - Any newly introduced SKU present in
inventory_transactionswith no row ininventory_baselinestarts from an implicit baseline of0. - Treat missing (
NULL)stock_countorchange_amountvalues as contributing0, and preserve negative balances when outflows exceed available units.
Rows may be returned in any order.
Input Schema
inventory_baseline
| Column | Type | Description |
|---|---|---|
product_id |
INTEGER |
SKU identifier |
stock_count |
INTEGER |
Opening unit count recorded in the baseline snapshot |
inventory_transactions
| Column | Type | Description |
|---|---|---|
transaction_id |
INTEGER |
Unique movement record identifier |
product_id |
INTEGER |
SKU identifier affected by the movement |
change_amount |
INTEGER |
Signed unit delta (positive for restocks, negative for shipments) |
transaction_date |
TIMESTAMP |
Timestamp when the movement occurred |
Examples
Example 1
Input (inventory_baseline):
| product_id | stock_count |
|---|---|
| 10 | 250 |
| 20 | 80 |
| 30 | 45 |
Input (inventory_transactions):
| transaction_id | product_id | change_amount | transaction_date |
|---|---|---|---|
| 101 | 10 | -35 | 2025-02-03 09:00:00 |
| 102 | 10 | 15 | 2025-02-07 14:15:00 |
| 103 | 20 | -20 | 2025-02-11 11:30:00 |
Output:
| product_id | current_stock |
|---|---|
| 10 | 230 |
| 20 | 60 |
| 30 | 45 |
Walk-through:
- SKU 10 starts at 250 and undergoes -35 then +15, ending at 250 - 35 + 15 = 230.
- SKU 20 starts at 80 and ships 20 units, ending at 60.
- SKU 30 has no recorded movements, so its balance stays 45.
Example 2
Input (inventory_baseline):
| product_id | stock_count |
|---|---|
| 50 | 12 |
Input (inventory_transactions):
| transaction_id | product_id | change_amount | transaction_date |
|---|---|---|---|
| 201 | 40 | 30 | 2025-03-01 08:00:00 |
| 202 | 40 | -8 | 2025-03-04 16:45:00 |
| 203 | 50 | -15 | 2025-03-05 10:20:00 |
Output:
| product_id | current_stock |
|---|---|
| 40 | 22 |
| 50 | -3 |
Walk-through:
- SKU 40 does not appear in inventory_baseline, so it starts at 0 and ends at 0 + 30 - 8 = 22.
- SKU 50 starts at 12 and has -15 deducted, yielding -3 (backordered balances are not clamped to zero).
Constraints
- A
product_idininventory_transactionsis not guaranteed to exist ininventory_baseline, and aproduct_idininventory_baselinemay have zero rows ininventory_transactions. inventory_baselinemay occasionally hold multiple snapshot rows for the sameproduct_id(for instance across warehouses), whose counts sum together once.- Both tables may contain
NULLnumeric entries or be completely empty.
Step-by-step walkthrough
Understand the tables and the goal
We are given two inventory tables:
inventory_baseline(product_id, stock_count): initial inventory recorded at the start of the year;inventory_transactions(transaction_id, product_id, change_amount, transaction_date): every stock movement since then (+for incoming restocks,-for outgoing sales).
We must return one row per
product_idwith(product_id, current_stock), where:current_stock = (sum of baseline stock_count) + (sum of transaction change_amount)Two asymmetric coverage rules make this interesting:
- A product can sit in
inventory_baselinewith zero transactions all year (its current stock is its baseline). - A new product can appear in
inventory_transactionswith no row ininventory_baseline(its starting baseline is0).
Avoid the join fan-out trap by pre-aggregating
A tempting first attempt joins
inventory_baselinedirectly toinventory_transactionsand sums both columns together:-- WRONG: repeats stock_count once for every matching transaction! SELECT b.product_id, SUM(b.stock_count) + SUM(t.change_amount) AS current_stock FROM inventory_baseline AS b LEFT JOIN inventory_transactions AS t ON t.product_id = b.product_id GROUP BY b.product_idWhy does this fail? Joining 1 baseline row (
250) to 2 transaction rows (-35and+15) produces 2 joined rows, duplicating250on every row:Joined rows before GROUP BY (fan-out!): product_id | b.stock_count | t.change_amount -----------+---------------+---------------- 10 | 250 | -35 10 | 250 | +15 SUM: | 500 | -20 --> 500 + (-20) = 480 (WRONG! Should be 230)To prevent row multiplication completely, aggregate each table to one row per
product_idfirst inside two CTEs (Common Table Expressions — named temporary query blocks written withWITH). Pre-aggregating both sides also handles any product that happens to have multiple baseline entries (for example, across two warehouses):WITH baseline_totals AS ( -- Sum initial stock per product (also guards against duplicate baseline rows) SELECT product_id, SUM(stock_count) AS baseline_stock FROM inventory_baseline GROUP BY product_id ), transaction_totals AS ( -- Pre-aggregate movements to one net change per product before joining SELECT product_id, SUM(change_amount) AS total_change FROM inventory_transactions GROUP BY product_id )Build the complete product list with UNION
If we wrote
FROM baseline_totals LEFT JOIN transaction_totals, we would keep baseline-only products — but we would lose any new product that exists only ininventory_transactions.What we want is every distinct
product_idthat appears in either table. While some SQL dialects offerFULL OUTER JOIN, a clean, universal pattern that works identically in SQLite, MySQL, PostgreSQL, and Snowflake is taking theUNIONof product IDs from both summaries (UNIONautomatically removes duplicate IDs):all_products AS ( -- Collect every distinct product ID present in either table (UNION removes duplicates) SELECT product_id FROM baseline_totals UNION SELECT product_id FROM transaction_totals )Left join both summaries and replace NULLs with COALESCE
Now
all_productshas exactly one row perproduct_id, and bothbaseline_totalsandtransaction_totalshave at most one row perproduct_id. Joining them with twoLEFT JOINs is strictly one-to-one!There is one last SQL detail: when a product is missing from one side (or all its values on that side were
NULL), its sum comes back asNULL. In SQL arithmetic,100 + NULLevaluates toNULL— not100! Wrapping each side inCOALESCE(x, 0)(which returnsxwhen non-NULL, and falls back to0whenxisNULL) turns missing sides into0cleanly:SELECT a.product_id, -- COALESCE turns missing or all-NULL sums into 0 so NULL + x never becomes NULL COALESCE(b.baseline_stock, 0) + COALESCE(t.total_change, 0) AS current_stock FROM all_products AS a -- LEFT JOIN both summaries so products missing from either table are still kept LEFT JOIN baseline_totals AS b ON b.product_id = a.product_id LEFT JOIN transaction_totals AS t ON t.product_id = a.product_idWalk through Example 1 (plus a baseline-missing SKU)
Let's trace Example 1 (
10,20,30) alongside SKU40from Example 2 (no baseline, movements+30and-8) to see every case at once:product_id | b.baseline_stock | t.total_change | COALESCE(b, 0) + COALESCE(t, 0) -----------+------------------+-----------------+-------------------------------- 10 | 250 | -20 (-35 + 15) | 250 + (-20) = 230 (Example 1) 20 | 80 | -20 | 80 + (-20) = 60 (Example 1) 30 | 45 | NULL | 45 + 0 = 45 (no transactions) 40 | NULL | +22 (30 - 8) | 0 + 22 = 22 (missing from baseline)For Example 1 alone,
all_productscontains10,20, and30, returning(10, 230),(20, 60), and(30, 45).Complete SQL query
Putting all three CTEs and the final
SELECTtogether gives the complete solution:WITH baseline_totals AS ( -- Sum initial stock per product (also guards against duplicate baseline rows) SELECT product_id, SUM(stock_count) AS baseline_stock FROM inventory_baseline GROUP BY product_id ), transaction_totals AS ( -- Pre-aggregate movements to one net change per product before joining SELECT product_id, SUM(change_amount) AS total_change FROM inventory_transactions GROUP BY product_id ), all_products AS ( -- Collect every distinct product ID present in either table (UNION removes duplicates) SELECT product_id FROM baseline_totals UNION SELECT product_id FROM transaction_totals ) SELECT a.product_id, -- COALESCE turns missing or all-NULL sums into 0 so NULL + x never becomes NULL COALESCE(b.baseline_stock, 0) + COALESCE(t.total_change, 0) AS current_stock FROM all_products AS a -- LEFT JOIN both summaries so products missing from either table are still kept LEFT JOIN baseline_totals AS b ON b.product_id = a.product_id LEFT JOIN transaction_totals AS t ON t.product_id = a.product_id✅ Submit now — all tests should pass.
Intuition & how it works
Computing current product stock works just like balancing a bank account: you start with the January 1 opening balance (inventory_baseline) and add up every deposit and withdrawal recorded since then (inventory_transactions). Some products sat on the shelf all year without a single transaction, while newer products arrived mid-year with transactions but no January 1 baseline entry (meaning their opening balance was 0), and our inventory report must include both.
Two obvious SQL approaches go wrong right away. First, joining inventory_baseline directly to inventory_transactions and writing SUM(stock_count) + SUM(change_amount) causes join fan-out (row multiplication): if Product 10 has a baseline of 250 and 4 transactions, the join repeats 250 on all 4 matched rows and inflates the baseline to 1000! Second, starting FROM inventory_baseline LEFT JOIN ... keeps quiet baseline products, but silently drops any new product that appears only in inventory_transactions, and forgetting COALESCE(..., 0) (which replaces NULL with a fallback 0) causes 250 + NULL to evaluate to NULL.
Instead, we break the query into three clean CTEs (Common Table Expressions — named temporary subqueries introduced with WITH):
1. baseline_totals and transaction_totals pre-aggregate each table by product_id so each product has at most one row on either side (eliminating join fan-out completely).
2. all_products combines product_ids from both summaries with UNION (which merges two result sets and removes duplicate IDs).
3. The final SELECT uses two LEFT JOINs (joins that keep every row on the left and pad missing matches with NULL) from all_products and adds COALESCE(b.baseline_stock, 0) + COALESCE(t.total_change, 0).
Trace three products from Examples 1 and 2 to see how every case behaves:
- Product 10 (baseline 250, changes -35 and +15): baseline_totals gives 250, transaction_totals gives -20 -> 250 + (-20) = 230.
- Product 30 (baseline 45, no transactions): baseline_totals gives 45, transaction_totals is NULL -> 45 + 0 = 45.
- Product 40 (no baseline, changes +30 and -8): baseline_totals is NULL, transaction_totals gives 22 -> 0 + 22 = 22.
Complexity
Let B be the number of rows in inventory_baseline, T be the number of rows in inventory_transactions, and P be the total number of distinct product_ids across both tables (P <= B + T).
- Time: Pre-aggregating the baseline and transaction tables scans B and T rows once, taking O(B + T) time with hash aggregation or O(B log B + T log T) when the engine sorts rows to group them. Deduplicating the two product lists with
UNIONand performing two 1-to-1LEFT JOINs over P distinct products takes O(P log P) with sorting or O(P) with hash tables, so the scan of T transactions dominates. - Space: O(P) memory to hold the per-product summaries and distinct product IDs under hash aggregation (or O(B + T) temporary sort space if the engine sorts unindexed tables).
Indexes that help in production:
- A covering index (an index containing all columns a query reads so the table heap is untouched) on inventory_transactions(product_id, change_amount) lets the engine read movements already grouped by product_id and sum change_amount in a single sequential index scan without sorting.
- Indexing inventory_baseline(product_id, stock_count) (or making product_id its primary key) accelerates the baseline side the same way.
Edge cases
- Product in baseline with zero transactions:
t.total_changeisNULL,COALESCE(t.total_change, 0)becomes0, and its baseline (even if0) is preserved. - New product appearing only in transactions: Included via
all_products, withCOALESCE(b.baseline_stock, 0)supplying a starting baseline of0. - Multiple baseline rows for the same product (e.g., per-warehouse snapshots):
baseline_totalssums them to one row perproduct_idbefore joining, preventing duplicate output rows and transaction multiplication. NULLstock_countorNULLchange_amount: SQL'sSUM()ignoresNULLentries and returnsNULLif every row in a group isNULL;COALESCE(..., 0)safely turns thatNULLinto0.- Negative stock (backorders or overselling): Preserved as a negative integer (e.g.,
3 + (-5) = -2) rather than clipped to0, surfacing inventory discrepancies accurately. - Both tables empty:
all_productshas zero rows, returning an empty result with columnsproduct_idandcurrent_stock.
Common mistakes
- Joining raw transactions to baseline before grouping: Multiplies
stock_countby the number of transactions for that product (join fan-out). - Using
FROM inventory_baseline LEFT JOIN ...withoutUNIONorFULL OUTER JOIN: Silently drops products that were introduced after the start-of-year baseline. - Using
INNER JOIN: Drops both products with zero transactions and products missing from the baseline. - Omitting
COALESCE(..., 0): Becausex + NULLevaluates toNULLin SQL, any product missing from either table ends up withcurrent_stock = NULL. - Writing
SUM(b.stock_count + t.change_amount)across joined rows: Not only suffers from fan-out, but any row where one column isNULLturnsb.stock_count + t.change_amountintoNULL, throwing away the other non-NULLnumber on that row!
Alternative approaches
- Stack both tables with
UNION ALLand group once: Because the baseline is algebraically just an initial+stock_countmovement, you can stackinventory_baselineandinventory_transactionsvertically usingUNION ALL(which concatenates rows without deduplicating them) and run a singleGROUP BY product_id:
sql
WITH all_movements AS (
SELECT product_id, stock_count AS delta FROM inventory_baseline
UNION ALL
SELECT product_id, change_amount AS delta FROM inventory_transactions
)
SELECT
product_id,
COALESCE(SUM(delta), 0) AS current_stock
FROM all_movements
GROUP BY product_id
This requires zero joins and naturally keeps products from either table as well as duplicate baseline rows. Note one subtle difference if bad data ever contained `product_id = NULL`: `GROUP BY` bundles `NULL` keys together, so add `WHERE product_id IS NOT NULL` if `NULL` keys should be excluded.
FULL OUTER JOINbetweenbaseline_totalsandtransaction_totals: SelectingCOALESCE(b.product_id, t.product_id) AS product_idoverbaseline_totals b FULL OUTER JOIN transaction_totals t ON b.product_id = t.product_idavoids theall_productsCTE (supported in PostgreSQL, Snowflake, and SQLite 3.39+, though not in MySQL).
Follow-up questions
- How would you filter the output so only SKUs whose net stock has fallen below a target restock minimum are returned? Keep the current-stock calculation inside a CTE (say
current_inventory) and filter in the outer query withWHERE current_stock < :reorder_threshold(or useHAVING COALESCE(SUM(delta), 0) < :reorder_thresholdin theUNION ALLversion). Never filter insidetransaction_totals, because whether a product needs reordering depends onbaseline + net_transactionscombined, not on transactions alone. If each SKU has its own custom threshold,LEFT JOIN reorder_rules r ON r.product_id = c.product_idand filterWHERE c.current_stock < r.min_stock. - How would you adjust the query to reconstruct each product's inventory balance at the end of a past calendar date? Add a timestamp filter inside
transaction_totalsbeforeGROUP BY:WHERE transaction_date < '2025-02-08 00:00:00'(using an exclusive upper bound at midnight of the next day so every movement on2025-02-07is included). On Example 1 at the close of2025-02-07, SKU10stands at250 - 35 + 15 = 230while SKU20remains at its opening80because its-20shipment happened later on2025-02-11(and if a new SKU had no baseline row and its earliest movement occurred after the cutoff date, filteringtransaction_totalsnaturally leaves it out of that historical snapshot). - How would you redesign the storage and query pattern once the ledger accumulates billions of movement records? Re-scanning billions of historical rows on every query is wasteful; instead, roll forward periodic snapshots (for example, a nightly or monthly
inventory_snapshots(snapshot_date, product_id, stock_count)table). To compute stock right now, start from the latest snapshot and suminventory_transactionsonly wheretransaction_date >= latest_snapshot_time, pruning older daily partitions completely (and keying snapshots on ingestion sequence /transaction_idwatermark if back-dated late events can arrive). For low-latency storefront reads, maintain a livecurrent_stockcounter table updated atomically inside the same ACID database transaction that inserts eachinventory_transactionsledger row, paired with a nightly reconciliation job against the immutable ledger to catch any drift.
Follow-up questions
- How would you filter the output so only SKUs whose net stock has fallen below a target restock minimum are returned?
- How would you adjust the query to reconstruct each product's inventory balance at the end of a past calendar date?
- How would you redesign the storage and query pattern once the ledger accumulates billions of movement records?
Similar questions
- Minimum Added Stones for Equal Subtree Sums
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager