Trending

World technology news

→
Orders and delivery matches across two warehouses. North 102, North 103, and South 104 remain open.
Software Engineering · 2026
Software Engineering

Reconcile missing deliveries with NOT EXISTS in SQLite

Use SQLite to find outstanding orders in a delivery feed with missing order numbers and repeated attempts.

Developer's JournalPublished: Nov 28, 20266 min read
Reading progress0%
In this article
  1. Define what counts as an outstanding order
  2. Build a fixture with missing keys and repeated attempts
  3. See how one NULL empties a NOT IN report
  4. Look for an exact successful match with NOT EXISTS
  5. Compare index access before and after
  6. Track orphan messages and the time of the report
  7. Roll out against a known set of orders

Define what counts as an outstanding order

A distribution team reconciles its order list with delivery results from a carrier every hour. Two warehouses can issue the same order number. Retries arrive as separate rows and some carrier messages arrive without any order number. The team needs the orders with no successful delivery. A valid match therefore requires the warehouse, the order number, and a delivered state. Failed attempts leave orders open, and repeat deliveries carry the same existence result as one successful delivery. This example treats delivery as a terminal business event. If deliveries can be reversed, decide which carrier event represents the effective state before writing the reconciliation. A view that resolves events by sequence and a stable source event identifier can provide that state. This lets a revoked delivery reappear in the open list when that is the intended business rule.

Build a fixture with missing keys and repeated attempts

Create both tables in an empty SQLite database. Warehouse and order number form the primary key of an order. Each delivery attempt has its own local identity, so more than one attempt can belong to the same order. North order 101 was delivered. North order 102 has a failed attempt, and north 103 has none. The south warehouse also uses order number 103 and has two successful reports for it. South 104 has no attempt. Finally, one north message reports success without an order number. Keep this message in the raw data so you can trace the data quality problem. Filling its missing number with an arbitrary default could close an unrelated order. The separate diagnostics count unassigned messages without treating them as deliveries.

Database access flowConceptual sketch · summary of the article's technical flow
CREATE TABLE orders (
  warehouse TEXT NOT NULL,
  order_no INTEGER NOT NULL,
  PRIMARY KEY (warehouse, order_no)
);
CREATE TABLE delivery_attempts (
  id INTEGER PRIMARY KEY,
  warehouse TEXT NOT NULL,
  order_no INTEGER,
  state TEXT NOT NULL CHECK (state IN ('failed', 'delivered'))
);
INSERT INTO orders VALUES ('north', 101), ('north', 102),
  ('north', 103), ('south', 103), ('south', 104);
INSERT INTO delivery_attempts VALUES
  (1, 'north', 101, 'delivered'),
  (2, 'north', 102, 'failed'),
  (3, 'north', NULL, 'delivered'),
  (4, 'south', 103, 'delivered'),
  (5, 'south', 103, 'delivered');

See how one NULL empties a NOT IN report

Run the first query against the north warehouse only. Its subquery returns 101 and NULL. Membership is known for 101, so the negated condition is false. For 102 and 103, comparison with 101 is false and comparison with NULL is unknown. With that result set, SQLite evaluates the NOT IN condition as NULL for both orders. The outer WHERE clause keeps only true conditions, so the report returns no rows. An operator could read that as a fully delivered batch. Run the inner query by itself to see the problematic value. Filtering out NULL inside the subquery can fix this particular expression. Here the reconciliation involves a composite identity and a success condition, which is a good reason to express the whole match in one correlated query.

SELECT o.order_no
FROM orders AS o
WHERE o.warehouse = 'north'
  AND o.order_no NOT IN (
    SELECT a.order_no FROM delivery_attempts AS a
    WHERE a.warehouse = o.warehouse AND a.state = 'delivered'
  )
ORDER BY o.order_no;

Look for an exact successful match with NOT EXISTS

For each order, the correlated subquery looks for a delivered attempt with the same warehouse and order number. EXISTS is true when a row meets all three conditions. A failed attempt does not satisfy the state condition, and an attempt with a missing order number cannot satisfy the equality. Repeated successful attempts leave the existence test unchanged. Read the expected results in order as north 102, north 103, and south 104. South 103 is the deliberate boundary case: its successful deliveries must leave the north order with the same number open. SELECT 1 makes the intent of the subquery easy to see because the expression looks only for the presence of a row. Keep the expected results beside the fixture so a subsequent query change can be checked against all three cases.

SELECT o.warehouse, o.order_no
FROM orders AS o
WHERE NOT EXISTS (
  SELECT 1
  FROM delivery_attempts AS a
  WHERE a.warehouse = o.warehouse
    AND a.order_no = o.order_no
    AND a.state = 'delivered'
)
ORDER BY o.warehouse, o.order_no;

Compare index access before and after

A large attempt table makes repeated full scans expensive. Add a composite index across the three equality columns and compare EXPLAIN QUERY PLAN output with the query text held constant. On the local fixture the inner attempt scan becomes an indexed search using delivery_attempt_lookup. Scanning the outer orders remains reasonable when the task must reconcile the whole order book. The query plan describes how SQLite looks for rows. Measure elapsed time and ingestion costs separately on a representative dataset. The share of failed and successful attempts, their distribution across warehouses, and the daily insert volume all affect the outcome. A partial index limited to successful attempts may also fit this exact query. Compare its plan and maintenance cost before adopting it. Treat the human-readable plan as diagnostic output whose formatting may change between SQLite versions.

CREATE INDEX delivery_attempt_lookup
ON delivery_attempts(warehouse, order_no, state);

EXPLAIN QUERY PLAN
SELECT o.warehouse, o.order_no
FROM orders AS o
WHERE NOT EXISTS (
  SELECT 1
  FROM delivery_attempts AS a
  WHERE a.warehouse = o.warehouse
    AND a.order_no = o.order_no
    AND a.state = 'delivered'
)
ORDER BY o.warehouse, o.order_no;

Track orphan messages and the time of the report

Track the outstanding list alongside the number of carrier attempts that lack an order number. The first drives fulfillment work and the second drives data correction. The fixture should report one unassigned message from north. If the carrier later sends a correction, retain the source message identity so the correction can be reprocessed safely. When both reports run on SQLite, use the same read transaction and connection if they need to describe the same database snapshot. When they draw on different systems, record the cutoff applied to each input. After a successful delivery arrives for north 102, only that order should leave the outstanding list. Repeating the successful message should leave the results unchanged. Those cases are covered by running the same reconciliation after each insert in the fixture.

SELECT warehouse, COUNT(*) AS missing_order_no
FROM delivery_attempts
WHERE order_no IS NULL
GROUP BY warehouse
ORDER BY warehouse;

Roll out against a known set of orders

Start with one warehouse and a set of orders that operators have already reconciled by hand. Compare a few open orders with the carrier history at the end of a shift. Validate the warehouse key on both inputs. A carrier might send the name of the north warehouse with a trailing space, which calls for a decision in the ingestion contract. Retain the original value if you normalize it. If the report creates work items, make each warehouse and order pair unique so a second run updates the same item. Recording when an item closes helps measure the delay between the delivery and the reconciliation.

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.