Smart Statistics · Practical SQL tutorial
SQL Running Balance Tutorial: Find Hidden Negative Stock
A positive closing balance can conceal a negative balance earlier in the day. Follow the movement sequence to find the exception that the daily total misses.
19 November 2026 · SQL Server / Azure SQL Database · UK operations
Product P100 · Leicester stock movement review
Evidence trail
A receipt restores the balance. It does not explain why the earlier issue took it below zero.
Illustrative example · All dashboard figures and statuses are invented.Find the point where the story stops adding up
A wholesaler issues goods before a receipt is recorded. By lunchtime, the ledger looks healthy again. A closing-stock report cannot show whether this was a late posting, a duplicated dispatch or a genuine shortage.
This tutorial creates a quantity balance after every movement. Use it for a retrospective exception review; it is not a live stock reservation system. You need access to SQL Server or Azure SQL Database and a query editor such as SQL Server Management Studio. Run the sample in an approved test environment; it creates only table variables.
Good output
Every balance traces to a movement, product, location, opening position and approved sequence. Reviewers can explain the first negative point.
A misleading shortcut
Summing all sites together can let stock in Derby conceal a Leicester exception. Daily aggregation can hide the sequence within the day.
Set the stock boundary
Agree one row per posted movement, quantities in a single base unit, receipts positive and issues negative. Product and location form the balance partition. Add lot, ownership or stock-status keys if the business treats those balances separately.
The opening snapshot must represent the position immediately before the included movements. Retain its timestamp and batch ID in production. Do not include the same receipt in both the opening snapshot and the movement extract.
Decide whether you need event-time history or posting-time history. Retain both timestamps when late entry matters. If only dates are available, report daily balances and state that intraday negative positions cannot be established reliably.
Run the complete batch
Open a new query in your test database and run the whole block. P100 starts with 10 units in Leicester and 4 in Derby. The two Leicester issues share a timestamp deliberately, so the sequence rule is visible.
-- Illustrative example. Run the complete batch in a test query window.
-- Target: SQL Server or Azure SQL Database. No permanent objects created.
DECLARE @Opening TABLE (
ProductCode varchar(20) NOT NULL,
LocationCode varchar(20) NOT NULL,
OpeningQty decimal(19,3) NOT NULL,
PRIMARY KEY (ProductCode, LocationCode)
);
DECLARE @Movement TABLE (
MovementID int NOT NULL PRIMARY KEY,
ProductCode varchar(20) NOT NULL,
LocationCode varchar(20) NOT NULL,
EventAt datetime2(0) NOT NULL,
Quantity decimal(19,3) NOT NULL
);
-- Opening quantities are immediately before this sample's first event.
INSERT INTO @Opening VALUES ('P100','LEI',10),('P100','DER',4);
INSERT INTO @Movement VALUES
(101,'P100','LEI','2026-11-18T09:00:00',-8),
(102,'P100','LEI','2026-11-18T09:00:00',-5),
(103,'P100','LEI','2026-11-18T10:00:00',12),
(104,'P100','LEI','2026-11-18T11:00:00',-2),
(105,'P100','DER','2026-11-18T09:30:00',-1);
-- Never silently discard a movement whose opening balance is missing.
IF EXISTS (
SELECT 1
FROM @Movement AS m
LEFT JOIN @Opening AS o
ON o.ProductCode = m.ProductCode
AND o.LocationCode = m.LocationCode
WHERE o.ProductCode IS NULL
)
BEGIN
;THROW 50001, 'Missing opening balance: stop and investigate.', 1;
END;
;WITH Running AS (
SELECT m.MovementID, m.ProductCode, m.LocationCode,
m.EventAt, m.Quantity,
o.OpeningQty + SUM(m.Quantity) OVER (
PARTITION BY m.ProductCode, m.LocationCode
ORDER BY m.EventAt, m.MovementID
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS BalanceQty
FROM @Movement AS m
INNER JOIN @Opening AS o
ON o.ProductCode = m.ProductCode
AND o.LocationCode = m.LocationCode
)
SELECT MovementID, ProductCode, LocationCode, EventAt,
Quantity, BalanceQty,
CASE WHEN BalanceQty < 0 THEN 'REVIEW'
ELSE 'Non-negative' END AS ReviewStatus
FROM Running
ORDER BY ProductCode, LocationCode, EventAt, MovementID;
Why these clauses matter
PARTITION BY starts a separate balance for each product and location. ORDER BY EventAt, MovementID supplies an unambiguous sample sequence. The explicit ROWS frame accumulates rows through the current movement. Microsoft documents these window behaviours in its OVER clause reference.
Without an explicit frame, an ordered aggregate can default to a RANGE frame. With timestamp-only ordering, tied events can therefore share a cumulative result and conceal an intermediate balance. Keep both a unique approved order and an explicit row frame.
The sample rejects missing quantities through NOT NULL. That matters because SUM ignores null values. Do not turn unknown quantities into zero merely to make a load succeed.
Check the expected results
Illustrative example. The query displays Derby first, then Leicester. Three decimal places reflect the sample quantity type; all values below are units.
| Location | Movement | Quantity | Balance | Status |
|---|---|---|---|---|
| DER | 105 | −1 | 3 | Non-negative |
| LEI | 101 | −8 | 2 | Non-negative |
| LEI | 102 | −5 | −3 | REVIEW |
| LEI | 103 | +12 | 9 | Non-negative |
| LEI | 104 | −2 | 7 | Non-negative |
Reconcile Leicester: 10 − 8 − 5 + 12 − 2 = 7. Derby remains separate: 4 − 1 = 3. A combined closing total of 10 says nothing about Leicester’s earlier −3.
Before adapting this to production, test missing openings, repeated movement IDs, tied timestamps and another product. Check negative opening snapshots separately: a partition with no movements produces no row in this movement report, even when its opening balance is negative.
Operate the exception review
Warehouse ownership
Assign each exception to a stock controller. Record a cause, evidence, action and review date. Separate late receipts, wrong units, duplicate issues and genuine shortages. Never auto-adjust stock just to remove a red flag.
Technical ownership
Keep the opening snapshot and movement extract aligned to a completed batch. Validate keys and units before the calculation. A late or backdated movement requires recalculation from the affected point, not just the latest day.
Production design
Use persistent staging and an agreed refresh cadence for repeatable reporting. Assess an index beginning with product, location and ordering columns against actual query plans and write costs. Do not assume the small table-variable demo predicts production performance.
Adoption and impact
Pilot one site with its stock controller. Review exceptions alongside source paperwork, then track time to resolve, repeat causes and manual investigation time. Measure negative episodes separately from negative rows: several consecutive rows can describe one episode.
A useful baseline compares the same scope and extraction cut-off over time. Falling exception counts may mean better posting discipline, but may also mean missing movements. Keep completeness checks alongside the outcome measures.
Is the pilot ready?
Tick only controls supported by evidence. This local checklist is a preparation aid, not an audit certification; selections are not saved or transmitted.
Frequently asked questions
Does negative stock prove a physical shortage?
No. It can reflect late receipts, incorrect units, duplicate issues or event-order problems. Investigate the source movements before concluding that stock was physically unavailable.
Why not sort only by the movement timestamp?
Several movements can share a timestamp. Use a unique, approved sequence within each product and location. A technical ID makes the order repeatable, but does not prove the real-world sequence.
Can I filter the start date before calculating the balance?
Only if you supply a validated opening balance immediately before that start date. Otherwise you remove earlier movements and calculate an incomplete balance.
Is this a stock valuation calculation?
No. This tutorial calculates quantities in one agreed unit. It does not calculate FIFO cost, weighted-average cost, available-to-promise quantities or financial stock valuation.
Turn stock exceptions into an owned review process
Smart Statistics can help you connect stock movements, validate the balance logic and build a clear Power BI review report. Start with one site, an agreed data boundary and an owner who can act on the evidence.