Data Management and SQL for Business — Quantitative Investigations
These original investigations extend the existing six-unit course, its published companions and assigned readings. Reproduce a worked result, solve the changed record without the answer, then inspect the failure assumptions. The executable laboratory provides independent calculations and transactional failure tests.
Open the course · Run and modify the laboratory
COURSE UNIT 4
Many-to-many joins, temporal cohorts and a reconciled result
A join is a multiplication of matching row combinations. If an order has two payment rows and three refund rows, joining both raw child tables to that order produces six combinations. Summing payment amounts repeats each payment three times; summing refunds repeats each refund twice. DISTINCT on the numeric amount is not a repair because equal-value legitimate events can be different records. Aggregate each child to the intended parent grain before combining them.
Time changes the metric as well as the join. Orders created during January, payments received during January and refunds issued during January are different eligible event sets. A January order can receive a February payment; a January payment can concern a December order. Define whether the report is a cash-period event measure, an order-cohort collection measure or an as-of receivable. None should be casually labeled revenue without the relevant recognition rules.
Use half-open time intervals such as event_time ≥ start and event_time < next_start. They avoid having to guess the final fractional second of a month. Store an explicit time basis and account for the relevant business timezone before assigning periods. The fictional date-only fixture has no timezone conversion problem; a production timestamp system does. A clean SQL predicate does not resolve an ambiguous business definition.
Null and zero need deliberate treatment. A missing child aggregate after a left join may reasonably become zero when it means no recorded events. An unknown amount or an unclassified event should not automatically become zero. COUNT(*) after an outer join can count a placeholder row, whereas counting a nonnull child key counts matched events. Reconcile totals and row counts against independently understood source events, including orders with no payments and equal-value distinct payments.
A report is an executable claim with a lineage. Preserve the query, parameters, source snapshot and metric contract. Test a small hand-reconciled fixture before running a large dataset. If a business total changes, distinguish a query correction, changed data, a revised eligibility rule and actual performance; they imply different explanations.
Work from this record
A fictional order has two distinct payments of 5,000 cents each: one on January 31 and one on February 1. It has refunds of 1,000 and 2,000 cents, both in February. A raw payment-refund join has four rows and yields 20,000 payment cents minus 6,000 refund cents = 14,000, which is wrong. Aggregate separately: 10,000−3,000 = 7,000 lifetime net collections. January cash-period net is 5,000; February is 5,000−3,000 = 2,000. The January order cohort may include all 7,000 only if its as-of horizon includes those February events. SUM(DISTINCT payment_amount) would incorrectly reduce the two real equal payments to 5,000.
Independent transfer
Add an unrelated order created in December with a 4,000-cent payment on January 15. Calculate January cash-period net and explain whether the January-created-order cohort changes. State the correct grain for combining event aggregates.
Compare the reasoning after your attempt
January cash-period net becomes 9,000 cents. The January-created-order cohort does not gain the December order merely because its payment occurred in January. Aggregate payment and refund events separately at the order grain for cohort reporting, or aggregate the signed event stream at the period grain for cash-period reporting. Keep the time and eligibility contract explicit.
Continue in the course reader
COURSE UNIT 5
Enforce a cross-row invariant under rollback, retry and contention
A CHECK constraint can validate one row, but a business invariant can span several rows and tables. Total refunds for an order must not exceed its recorded eligible payments in the fictional ledger below. Checking that rule in application memory and inserting later leaves a race: two requests can each observe the same available balance and both consume it. Protect the read-check-write sequence with an appropriate database transaction or atomic conditional write.
SQLite allows multiple readers but serializes writers. BEGIN IMMEDIATE attempts to establish a write transaction before the critical read; another writer can receive a busy result according to configuration and timing. This behavior is engine-specific, so do not transfer a locking claim to another database without checking its isolation semantics. A bounded retry may be appropriate for contention, but the whole operation must remain safe to retry and must not turn a changed request into an apparent duplicate success.
An operation identifier establishes identity. If refund R already exists with the same order and amount, an exact retry can return the established result. If R is reused with different contents, reject the conflict. Equal amounts under different identifiers can be separate legitimate refunds, subject to the aggregate invariant. The uniqueness constraint should enforce identity in the database, while content comparison determines whether a duplicate is a valid retry.
Audit insertion and business mutation belong to the same transaction when the promise is that every mutation has a durable audit record. A test should deliberately fail the audit insertion after inserting the refund and then inspect persisted state. Merely catching an exception does not demonstrate rollback. Some database errors undo only a statement and leave the transaction active, so the application must execute the intended rollback on failure rather than assume every exception ends the transaction.
Reconcile ambiguous completion. If the client times out after commit, a fresh operation ID can create another refund. Reuse the original identity or query its established result. Recovery must separate an uncommitted attempt, a committed event with a lost response and a conflicting request. Preserve authorization at the server boundary as well; an internally correct refund helper does not establish that a caller may access the order.
Work from this record
A fictional order has 10,000 cents of eligible payments and 3,000 already refunded. Two fresh requests each seek 4,000. A protected first transaction sees 7,000 available and commits, leaving 3,000. The second transaction must then reject 4,000. An unprotected check can let both see 7,000 and produce 11,000 refunded in total. If the first audit insertion fails, its refund must roll back so available capacity remains 7,000. An exact retry after a successful commit returns the recorded event and consumes no additional capacity.
Independent transfer
Write tests for exact retry, changed contents under the same ID, two equal-value distinct events, an over-refund attempt and forced audit failure. Which assertion proves the audit-failure path preserved the invariant?
Compare the reasoning after your attempt
After forced failure, assert that no new refund or audit row exists and that total refunded amount remains exactly its pre-transaction value. An exception alone is insufficient. For concurrency, verify the persisted sum as well as response outcomes; only one of the competing 4,000-cent requests can commit against 7,000 available. Distinct equal-value events are not deduplicated by amount.
Continue in the course reader
Sources and reading boundary
The existing course readings remain assigned. New formulas, fictional datasets and solutions above are original Academy teaching. The links below provide primary technical references; MIT examples are used only in the separate review to inspect instructional demands.