Trending

World technology news

→
Store A sorts two events at the same time by IDs 101 and 103. The balances are 10, 7 and 12 boxes.
Software Engineering · 2026
Software Engineering

Calculate stock balances for tied timestamps in SQLite

Use a stable tie breaker and a SQLite window function to compute the balance after each stock movement.

Developer's JournalPublished: Nov 30, 20266 min read
Reading progress0%
In this article
  1. Two stock movements in one minute
  2. Give tied timestamps a defined order
  3. Declare a row-by-row window frame
  4. Keep the opening balance in a report slice
  5. Run the checks in a local SQLite database
  6. Account for late events in published reports

Two stock movements in one minute

A shop receives ten boxes at nine in the morning. Three boxes are sold in the same minute. Staff need a ledger with both entries and the stock balance after each entry. A query that sorts by time alone gives both entries the same ordering value. The window frame also determines which rows contribute to each sum. This example calculates each store separately and orders entries by event time and a stable event ID. The receipt then shows ten boxes and the sale shows seven. A later example adds a correction that belongs between those entries. The ledger describes one product. A multi-product ledger should partition by product and store so movements for one SKU cannot change the balance of another SKU.

Give tied timestamps a defined order

In this table the event ID is a business rule for resolving a tie within the same minute. Establish what the ID means in a production ledger. A checkout terminal and a warehouse scanner can create timestamps from different clocks. A database arrival sequence does not establish the actual order in which those devices recorded work. This example defines the tie breaker explicitly and assumes stable IDs. It uses fixed-width HH:MM strings for one day, so text sorting follows the clock. Use an unambiguous timestamp representation and enough precision when a ledger spans several days or time zones. For local report boundaries, make the time zone explicit and check positions around midnight. Those cases often expose a stock movement included in the wrong day even when the daily totals look plausible.

Data processing architectureConceptual sketch · summary of the article's technical flow

Declare a row-by-row window frame

As a window function, SUM(delta) produces a value for every movement. PARTITION BY store keeps each store’s balance separate. The ORDER BY inside OVER determines the order of the calculation. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW covers the rows from the start of the partition through the current row. The comparison query orders the two nine o’clock entries by timestamp alone and leaves the frame implicit. SQLite’s default RANGE frame includes peers with the same ordering value, so both rows show seven. That can be a useful end-of-minute balance. For the balance after an individual entry, use the explicit row frame and the deterministic tie breaker. The outer SELECT orders the displayed result independently of the window calculation.

Keep the opening balance in a report slice

A screen might display only movements from 09:10 onward. Applying that time filter before calculating the window would discard the nine o’clock movements from the sum. This query uses a common table expression to calculate balances across the whole ledger and a final WHERE clause to select the displayed rows. The five-box receipt at 09:10 therefore shows twelve on hand. A larger ledger could combine a validated opening balance with a shorter range of underlying events. Agree on whether movements at the boundary belong in the opening snapshot or inside the new range. Counting them twice produces a wrong balance even when each piece of the query is correct on its own. Use entries on both sides of a boundary in acceptance examples.

Run the checks in a local SQLite database

Run the example with Python’s sqlite3 module. Store A begins with balances of ten, seven and twelve. Store B’s two boxes stay in their own partition. The 09:10 display filter returns the balance of twelve. The comparison query returns seven on both tied rows under the default frame. The final insert adds a one-box correction whose event ID fits between the first receipt and the sale. It takes A to nine at the new entry, six after the sale and eleven after the later receipt. Each assertion checks the balance alongside the event ID, which catches a different movement order even if the final total is identical. The example runs in a fresh in-memory database and uses no production data.

import sqlite3


with sqlite3.connect(':memory:') as db:
    db.execute('''CREATE TABLE stock_events (
        store TEXT NOT NULL,
        event_id INTEGER PRIMARY KEY,
        occurred_at TEXT NOT NULL,
        delta INTEGER NOT NULL
    )''')
    db.executemany('INSERT INTO stock_events VALUES (?, ?, ?, ?)', [
        ('A', 101, '09:00', 10),
        ('A', 103, '09:00', -3),
        ('A', 104, '09:10', 5),
        ('B', 201, '09:00', 2),
    ])
    query = '''
    WITH balances AS (
        SELECT store, event_id, occurred_at,
               SUM(delta) OVER (
                   PARTITION BY store
                   ORDER BY occurred_at, event_id
                   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
               ) AS balance
        FROM stock_events
    )
    SELECT store, event_id, balance
    FROM balances
    WHERE occurred_at >= ?
    ORDER BY store, occurred_at, event_id
    '''
    full = db.execute(query, ('00:00',)).fetchall()
    filtered = db.execute(query, ('09:10',)).fetchall()
    assert full == [('A', 101, 10), ('A', 103, 7), ('A', 104, 12), ('B', 201, 2)]
    assert filtered == [('A', 104, 12)]
    peers = db.execute('''SELECT SUM(delta) OVER (PARTITION BY store ORDER BY occurred_at)
                          FROM stock_events WHERE store = 'A' AND occurred_at = '09:00'
                          ORDER BY event_id''').fetchall()
    assert peers == [(7,), (7,)]
    db.execute("INSERT INTO stock_events VALUES ('A', 102, '09:00', -1)")
    revised = db.execute(query, ('00:00',)).fetchall()
    assert revised == [('A', 101, 10), ('A', 102, 9), ('A', 103, 6),
                       ('A', 104, 11), ('B', 201, 2)]
    print('SQLite', sqlite3.sqlite_version)
    print(full, filtered, peers, revised, sep='\n')

Account for late events in published reports

A late event changes balances on subsequent rows if it is inserted into an earlier position. If staff need to reconstruct a published report, record event time and ingestion time separately and define the data cutoff used by each report. Integer quantities suit boxes. A ledger of products sold by weight needs an explicit unit and precision policy. Design acceptance rows for returns, zero changes, empty stores and corrections that arrive after the report closes. If query performance matters, compare plans with EXPLAIN QUERY PLAN on representative date ranges and data sizes. This in-memory run verifies order and arithmetic. Capacity and latency measurements need workload and storage conditions that resemble the system running the ledger. If you persist daily opening balances, define when a historic correction invalidates the next snapshot. An explicit rebuild boundary gives downstream reports a repeatable starting point.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

Which alternative architecture would you try for the same problem?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.