← SQL and spreadsheet practice

SQL inventory · Original fictional case · Free files and answers

Reconcile the latest approved stock count

Warehouse staff upload multiple count attempts. Compare the latest approved count for each SKU with book stock, while retaining items that have never been approved.

Suggested time: 15–25 minutes. All records, companies, rates and work policies are invented for this exercise.

Your output contract

  1. Use approved=1 records only; timestamps are ISO text with no ties per SKU.
  2. Select the latest approved count independently for each SKU, not the latest timestamp for the warehouse.
  3. Return sku,book_units,counted_units,variance_units. If no approved count exists, leave both derived numbers NULL.

Required columns: sku, book_units, counted_units, variance_units. Row order is part of the contract. Empty output CSV fields represent NULL; zero remains 0.

Original source tables

stock

4 source rows · Download stock CSV

sku TEXTbook_units INTEGER
BOLT50
CABLE20
DRIVE10
LABEL0

counts

6 source rows · Download counts CSV

sku TEXTcounted_at TEXTapproved INTEGERunits INTEGER
BOLT2026-11-01T09:00148
BOLT2026-11-01T10:00149
CABLE2026-11-01T10:00019
CABLE2026-11-01T08:00121
LABEL2026-11-01T09:0010
DRIVE2026-11-01T09:0009

Plan the transformation

  1. Filter out drafts before ranking count attempts.
  2. Use ROW_NUMBER partitioned by SKU and descending timestamp.
  3. LEFT JOIN the top count to book stock; calculate counted minus book only for a real count.

Watch for this mistake

Replacing missing counts with zero invents a stock loss for DRIVE. Zero is a valid approved count for LABEL.

Run and check your SQLite result

The database runs locally in a worker. Use one SELECT or WITH query. Your query is saved on this device when storage is available. Download your SQL before clearing browser data.

Or work in Excel or another spreadsheet, then upload the final CSV with exactly the required columns.

Worked SQL and complete expected output

Approved variances sum to zero across three counted SKUs; DRIVE still requires a count.

WITH r AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY sku ORDER BY counted_at DESC) n FROM counts WHERE approved=1) SELECT s.sku,s.book_units,r.units counted_units,r.units-s.book_units variance_units FROM stock s LEFT JOIN r ON s.sku=r.sku AND r.n=1 ORDER BY s.sku;
skubook_unitscounted_unitsvariance_units
BOLT5049-1
CABLE20211
DRIVE10NULLNULL
LABEL000

Download reference SQL · Download complete expected CSV · Download an empty answer CSV · Download SQLite setup

What to pass to a colleague

Keep the checked output and SQL or spreadsheet result. Explain the exception policy, the cross-check above and any held records. The checker confirms this fixed case’s output; it does not evaluate arbitrary private business data.

SQLite SELECT, joins and aggregation reference · Continue with the larger workplace projects

Try another case