Lawfare Group → Knowledge Institute → Lawfare Academy

← Course syllabus · Related lesson

SQL: reconcile the order report and an idempotent correction

Current complete on-site edition 6

Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.

Cumulative data-system dossier, transfer models and 30-point rubric

Preserved original teaching integrated with complete current on-site preparation. Independent human subject review and observed learner testing remain pending.

Learning objectives

The complete reporting file

The fixture has customers 1,2,3; paid orders O1 for customer 1 and O2 for customer 2; and draft O3 with an unresolved NULL customer. O1 has two line items: two units at 12.00 and one at 30.00. O2 has one unit at 11.00; draft O3 has one at 7.00. Prices are transaction snapshots and implementation amounts use integer minor units. This is an operational billed/settled report, not a determination of financial-statement revenue recognition or actual tax treatment.

Settled payments are 30.00 and 24.00 for O1 and 11.00 for O2. Another O1 payment of 5.00 is pending and excluded by policy. Posted refunds are 6.00 for O1 and 2.00 for O2. Customer 1 has two tags, illustrating a separate one-to-many relationship. The report must retain one row per paid order, show billed, settled and posted-refund totals separately, and reconcile a defined net billed amount. Drafts and unresolved assignments must remain visible in exception checks rather than disappear from the database.

Aggregate each fact at the intended grain

O1 has billed and settled amounts of 54.00 and posted refunds of 6.00, yielding net billed 48.00. O2 has 11.00 billed and settled and 2.00 refunded, yielding 9.00. The paid-order report therefore totals billed 65.00, settled 65.00, refunds 8.00 and net billed 57.00. Draft billed amount 7.00 is separately excluded under the stated status policy.

A naive join of lines, settled payments and refunds on order identifier multiplies O1’s two lines by its two settled payments. Line and payment totals for O1 both become 108.00 and its 6.00 refund is repeated four times, becoming 24.00. Including O2 produces incorrect billed and settled totals of 119.00 and refunds of 26.00. DISTINCT applied to monetary values is not a repair: equal legitimate values can occur in different records. Aggregate each independent fact to order level first.

WITH line_totals AS (
  SELECT order_id, SUM(quantity * unit_price_cents) AS billed_cents
  FROM order_lines GROUP BY order_id
), payment_totals AS (
  SELECT order_id, SUM(amount_cents) AS settled_cents
  FROM payments WHERE status = 'settled' GROUP BY order_id
), refund_totals AS (
  SELECT order_id, SUM(amount_cents) AS refund_cents
  FROM refunds WHERE status = 'posted' GROUP BY order_id
)
SELECT o.order_id, COALESCE(l.billed_cents,0) AS billed_cents,
       COALESCE(p.settled_cents,0) AS settled_cents,
       COALESCE(r.refund_cents,0) AS refund_cents
FROM orders AS o
LEFT JOIN line_totals AS l ON l.order_id = o.order_id
LEFT JOIN payment_totals AS p ON p.order_id = o.order_id
LEFT JOIN refund_totals AS r ON r.order_id = o.order_id
WHERE o.status = 'paid'
ORDER BY o.order_id;

A zero fill here is a display rule for a missing aggregated relation under this specific report contract. It does not prove the missing payment or refund is factually zero in every source system. Keep data-quality checks for missing lines, unresolved payments and mismatched amounts.

A correction must be atomic, replay-safe and auditable

A new authorized synthetic refund command R3 requests 4.00 against O1. Apply the command record and refund record within one transaction, check the permitted amount against the stated settled/refunded balance, and use a stable command identity with a canonical payload. Replaying R3 with the identical payload returns the earlier result without creating another refund. Reusing R3 for 5.00 is a collision and must fail rather than silently alter history. An excessive refund must roll back both the proposed refund and its command marker.

After valid R3, posted refunds total 12.00 and net billed becomes 53.00. O1’s order, line prices and settled payments remain unchanged. An identical retry leaves the same total. The laboratory also tests an invalid oversized command, verifies no partial command record remains, and compares preserved orders and payments. These are ordinary synthetic transaction tests, not operations on Academy learner records or live payment systems.

The cumulative response must show the relational model, keys and nullable relationships; reporting population and status policy; grain of every aggregate; correct joins and row counts; transaction and replay behavior; preserved historical prices; reconciliation before and after the correction; and the limits of the operational measure. Explain how to establish a consistent read boundary and how an index experiment would preserve the answer. Study the complete six on-site studios and preserved normalization, migration, window and temporal-query chapters before optional self-assessment; external links are optional. Correct syntax without a trustworthy business interpretation does not meet the rubric. Independent subject review and learner testing remain separate statuses.

Worked example: Reconcile the correct and multiplied answers

The correct paid-order totals in minor units are 6,500 billed, 6,500 settled and 800 refunded. The naive multi-join gives 11,900, 11,900 and 2,600 because it repeats independent child facts. The difference is a row-grain error, not a rounding difference.

Worked example: A retry is different from a changed command

The first valid R3 adds 400 minor units to refunds, changing net billed from 5,700 to 5,300. The identical replay adds nothing. A changed payload with the same identity is rejected and preserves the stored original result.

Progressive optional practice

Attempt each problem before opening its model. Then revise the reasoning under the changed conditions.

Guided

Prepare the paid-order totals and the draft exception amount.

Compare the model reasoning

Billed 65.00, settled 65.00, posted refunds 8.00, net billed 57.00; draft amount 7.00 separately excluded.

Changed conditions

The pending 5.00 payment settles.

Compare the revised analysis

Settled total rises to 70.00 while billed and refund totals stay unchanged; investigate the operational overpayment rather than changing billed history.

Independent

Why does joining customer tags add a duplication risk?

Compare the model reasoning

A customer can have several tags. Use a defined tag-level report or an existence predicate where the intended output remains one row per order.

Changed conditions

Two distinct orders have the same billed total.

Compare the revised analysis

SUM(DISTINCT amount) would collapse legitimate equal amounts; preserve keys and aggregate at the intended grain.

Transfer

What must happen when an oversized refund fails after command registration is attempted?

Compare the model reasoning

The transaction must leave neither an applied refund nor a falsely completed command marker.

Changed conditions

The process crashes after commit but before acknowledging success.

Compare the revised analysis

An identical retry must find the committed command and avoid applying it twice; do not confuse a lost acknowledgement with an uncommitted transaction.

Preserved historical development snapshot · Course content review

Source readings and scope

SQLite: SELECT — Join, aggregate and grouping semantics for the stated dialect. Primary source checked October 27, 2026. The business records and numerical models are original synthetic exercises.

SQLite: transactions — Atomic transaction boundaries and error handling. Primary source checked October 27, 2026. The business records and numerical models are original synthetic exercises.

SQLite: foreign keys — Enforced relationships and connection-level configuration. Primary source checked October 27, 2026. The business records and numerical models are original synthetic exercises.

Reproduce the worked examples in Python 3. Standard library only; synthetic data; no production records or network access.

Complete optional data-system dossier: 30-point rubric

Use all six complete on-site studios and the nine preserved SQL applications. Prepare a model and dictionary with row grains; schema and enforced integrity; population/NULL/join/window report; transaction/replay/failure policy; analytical/security/recovery design; and a requirements-to-test release ledger. Use the preserved paid-order cumulative file as the main investigation. Independent enrollment, receipt-import, event, Q-order and classifier fixtures have different facts and must stay distinct.

Award 0–5 points each for model/history/identity; schema/domain/enforced references; report grain/population/SQL reconciliation; transaction/replay/failure preservation; governance/security/analytical-data boundaries; and reproducible tests, changed facts and operational limits. Zero is absent/unsupported,1–2 materially wrong,3 substantially correct but misses a material boundary,4 minor omission,5 accurate and traceable with an appropriate changed-fact revision. Total 30. Independent human review and observed human testing remain separate.

Full cumulative model: preserve facts and states

The original paid-order population containsO 1 andO 2. Billed 6500,settled 6500,postedrefund 800 andnetbilled 5700 cents reconcile; draft 700 andpending 500 remain separate exceptions. Raw child joins incorrectly yield 11900,11900,2600. Preaggregate each independent fact to order grain, preserve transaction prices and use counts/unknown flags rather than hiding missing measures. A valid 400 refund commandR 3 raises refunds to 1200 and net billed falls 5300. Exact replay adds none; changed payload under R 3 fails; an oversized command leaves neither a partial refund nor a false command marker. Original orders, lines and settled payments remain exact.

Changed model: resolve an import without inventing cash

The separate import has raw 31500 centsfrom four rows, unique receipts 24000 from three event IDs, assigned 20000 and unresolved 4000. A verified duplicate R 2 is a replay, not a new receipt; an equal-valued record with a distinct valid ID is new. Assigning R 3 to B changes attribution to A 12500/B 11500 without changing the 24000 total. A current warehouse view and a historical as-received snapshot can legitimately differ when labeled and preserved. Unknown measurements must not become zero.

Changed evidence: a fast or accurate system can still fail

The classifier's first threshold hasTP 15/FP 10/FN 5/TN 70,accuracy 85%,declared loss 600 at miss 100/false alarm 10. Alternative thresholdTP 18/FP 25/FN 2/TN 55 has accuracy 73%but loss 450. Threshold selection must not reuse an untouched-test claim. A 4 worker 80%-parallel model has ideal speedup 2.5,not 4,with real overhead additional. A 30 minute restore may meet 2 hourRTO while a 4 hour data-loss exposure fails 1 hourRPO. Document requirements, source cutoff, authority and actual evidence; agent checks are not independent human review.