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:

  1. product_id — the SKU's integer identifier.
  2. current_stock — an integer equal to that SKU's total starting stock_count in inventory_baseline plus the net sum of change_amount across all matching rows in inventory_transactions.

Apply these coverage and null-safety rules:

  • Any SKU present in inventory_baseline with zero rows in inventory_transactions retains its starting balance.
  • Any newly introduced SKU present in inventory_transactions with no row in inventory_baseline starts from an implicit baseline of 0.
  • Treat missing (NULL) stock_count or change_amount values as contributing 0, 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_id in inventory_transactions is not guaranteed to exist in inventory_baseline, and a product_id in inventory_baseline may have zero rows in inventory_transactions.
  • inventory_baseline may occasionally hold multiple snapshot rows for the same product_id (for instance across warehouses), whose counts sum together once.
  • Both tables may contain NULL numeric entries or be completely empty.

Step-by-step walkthrough

  1. 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_id with (product_id, current_stock), where:

    current_stock = (sum of baseline stock_count) + (sum of transaction change_amount)
    

    Two asymmetric coverage rules make this interesting:

    1. A product can sit in inventory_baseline with zero transactions all year (its current stock is its baseline).
    2. A new product can appear in inventory_transactions with no row in inventory_baseline (its starting baseline is 0).
  2. Avoid the join fan-out trap by pre-aggregating

    A tempting first attempt joins inventory_baseline directly to inventory_transactions and 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_id
    

    Why does this fail? Joining 1 baseline row (250) to 2 transaction rows (-35 and +15) produces 2 joined rows, duplicating 250 on 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_id first inside two CTEs (Common Table Expressions — named temporary query blocks written with WITH). 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
    )
    
  3. 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 in inventory_transactions.

    What we want is every distinct product_id that appears in either table. While some SQL dialects offer FULL OUTER JOIN, a clean, universal pattern that works identically in SQLite, MySQL, PostgreSQL, and Snowflake is taking the UNION of product IDs from both summaries (UNION automatically 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
    )
    
  4. Left join both summaries and replace NULLs with COALESCE

    Now all_products has exactly one row per product_id, and both baseline_totals and transaction_totals have at most one row per product_id. Joining them with two LEFT 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 as NULL. In SQL arithmetic, 100 + NULL evaluates to NULL — not 100! Wrapping each side in COALESCE(x, 0) (which returns x when non-NULL, and falls back to 0 when x is NULL) turns missing sides into 0 cleanly:

    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
    
  5. Walk through Example 1 (plus a baseline-missing SKU)

    Let's trace Example 1 (10, 20, 30) alongside SKU 40 from Example 2 (no baseline, movements +30 and -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_products contains 10, 20, and 30, returning (10, 230), (20, 60), and (30, 45).

  6. Complete SQL query

    Putting all three CTEs and the final SELECT together 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 UNION and performing two 1-to-1 LEFT 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_change is NULL, COALESCE(t.total_change, 0) becomes 0, and its baseline (even if 0) is preserved.
  • New product appearing only in transactions: Included via all_products, with COALESCE(b.baseline_stock, 0) supplying a starting baseline of 0.
  • Multiple baseline rows for the same product (e.g., per-warehouse snapshots): baseline_totals sums them to one row per product_id before joining, preventing duplicate output rows and transaction multiplication.
  • NULL stock_count or NULL change_amount: SQL's SUM() ignores NULL entries and returns NULL if every row in a group is NULL; COALESCE(..., 0) safely turns that NULL into 0.
  • Negative stock (backorders or overselling): Preserved as a negative integer (e.g., 3 + (-5) = -2) rather than clipped to 0, surfacing inventory discrepancies accurately.
  • Both tables empty: all_products has zero rows, returning an empty result with columns product_id and current_stock.

Common mistakes

  • Joining raw transactions to baseline before grouping: Multiplies stock_count by the number of transactions for that product (join fan-out).
  • Using FROM inventory_baseline LEFT JOIN ... without UNION or FULL 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): Because x + NULL evaluates to NULL in SQL, any product missing from either table ends up with current_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 is NULL turns b.stock_count + t.change_amount into NULL, throwing away the other non-NULL number on that row!

Alternative approaches

  • Stack both tables with UNION ALL and group once: Because the baseline is algebraically just an initial +stock_count movement, you can stack inventory_baseline and inventory_transactions vertically using UNION ALL (which concatenates rows without deduplicating them) and run a single GROUP 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 JOIN between baseline_totals and transaction_totals: Selecting COALESCE(b.product_id, t.product_id) AS product_id over baseline_totals b FULL OUTER JOIN transaction_totals t ON b.product_id = t.product_id avoids the all_products CTE (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 with WHERE current_stock < :reorder_threshold (or use HAVING COALESCE(SUM(delta), 0) < :reorder_threshold in the UNION ALL version). Never filter inside transaction_totals, because whether a product needs reordering depends on baseline + net_transactions combined, not on transactions alone. If each SKU has its own custom threshold, LEFT JOIN reorder_rules r ON r.product_id = c.product_id and filter WHERE 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_totals before GROUP BY: WHERE transaction_date < '2025-02-08 00:00:00' (using an exclusive upper bound at midnight of the next day so every movement on 2025-02-07 is included). On Example 1 at the close of 2025-02-07, SKU 10 stands at 250 - 35 + 15 = 230 while SKU 20 remains at its opening 80 because its -20 shipment happened later on 2025-02-11 (and if a new SKU had no baseline row and its earliest movement occurred after the cutoff date, filtering transaction_totals naturally 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 sum inventory_transactions only where transaction_date >= latest_snapshot_time, pruning older daily partitions completely (and keying snapshots on ingestion sequence / transaction_id watermark if back-dated late events can arrive). For low-latency storefront reads, maintain a live current_stock counter table updated atomically inside the same ACID database transaction that inserts each inventory_transactions ledger row, paired with a nightly reconciliation job against the immutable ledger to catch any drift.

Follow-up questions

Similar questions

More Reinforce Labs interview questions

All 2 Reinforce Labs questions →