Preserved original teaching and transfer history, integrated with complete current on-site preparation. Independent human review/testing remain pending.
A current value cannot answer every historical question
A salesperson's territory can change while earlier orders remain unchanged. If the order table stores salesperson_id and a separate salesperson table stores only the current territory, joining them may assign old revenue to today's territory. The SQL can execute without an error and still answer a different question from the one in the report title. Begin with the time question: territory when the order was placed, territory known when the report was produced, or territory currently responsible for that customer? These are distinct reporting policies.
The fictional fixture uses valid-time intervals with an inclusive start and exclusive end. A North assignment from 2026-01-01 to 2026-04-01 includes March 31 but excludes April 1. A South assignment starting April 1 owns that boundary date. For order dates, the predicate is valid_from <= order_date AND order_date < valid_to. A null end may mean continuing indefinitely and must be handled explicitly. Reusing an inclusive end on both adjacent intervals can match a boundary order twice. Merely adding DISTINCT to the output can hide the duplicated join without repairing its meaning.
An ordinary primary key on salesperson and interval start prevents duplicate starts. It does not prevent one interval from overlapping another with a different start. A row-level CHECK that the start precedes the end checks the internal ordering of one record, not mutual exclusion across all records. Cross-row temporal integrity requires additional enforcement appropriate to the database and write path. This laboratory detects overlaps with a self-join and treats the detection as a failed invariant, not as an automatic repair. A production solution also needs concurrency-safe enforcement, migration and recovery procedures; those remain outside this small SQLite fixture.
Reconcile cardinality with an explicit expected result
The fixture has three orders for salesperson 1: order 101 on March 31 for 100, order 102 on April 1 for 200 and order 103 on April 2 for 300. The salesperson changes from North to South on April 1. Under order-date territory attribution, the correct groups are North 100 and South 500. The correct total remains 600, and each order should match exactly one history row. A current-territory join would place all 600 in South. That result passes a grand-total check but fails the reporting-policy check. Totals alone cannot establish correct attribution.
Write two independent checks. First count history matches per order and require exactly one for this fixture. Second compare grouped results with the independently reasoned expected answer. Missing matches require deciding whether to reject the report, classify the order as unresolved or apply another documented policy. An inner join silently dropping unmatched orders is not an acceptable undocumented default. Overlapping intervals create more than one match; those must be resolved in the source or reported as exceptions before the revenue is summarized.
The attached script then introduces a conflicting West interval beginning March 15 and ending April 15. Each of the three orders now has two valid history matches. A naive sum doubles to 1200. The overlap detector and per-order cardinality check both reveal the defect. An analyst should not choose the alphabetically first territory or divide the revenue by two: those operations invent attribution rules. Restore a coherent history or publish an exception report while the disputed classification is resolved. The example separates numerical reconciliation, relational integrity and substantive business meaning so that passing one does not stand in for passing the others.
A query plan describes an implementation strategy, not correctness
After establishing the query's meaning, examine its access path. The reproduction creates a separate 10,000-row order fixture and runs the same customer-total query before and after adding an index on customer_id. It checks that both executions return the same total. It also prints EXPLAIN QUERY PLAN output so the learner can inspect the chosen path in the installed SQLite version. The equality of results is a semantic regression check; the plan is evidence about execution strategy. Neither proves that the query is the right business definition.
A selective equality predicate can benefit from an index because the engine may locate matching entries without visiting every table row. Maintaining that index also consumes storage and adds write work. If nearly all rows qualify, scanning can be reasonable. Do not teach the rule that SEARCH is always good and SCAN is always bad. Data distribution, selected columns, covering indexes, ordering, table size and statistics affect the choice. A tiny teaching database is particularly poor evidence for a production latency promise.
SQLite warns that the human-readable plan format can change. The exercise therefore records the actual version and output, but does not parse a particular English plan sentence as a stable application contract. The correctness assertions compare query results and invariants. A performance investigation would also specify representative data, warm and cold cache conditions, concurrent workload, timing method and distribution of response times. An index proposal should include a rollback plan and write-cost assessment. This laboratory deliberately makes no measured speedup claim; it teaches how to separate a reproducible result from an unmeasured performance hypothesis.
Worked example
Orders 101,102,103 are dated 2026-03-31, 2026-04-01 and 2026-04-02 for 100,200,300. North is valid from January 1 through the instant before April 1; South starts April 1. An alternative current-territory report assigns every order to South.
Using half-open date intervals, 101 matches North; 102 and 103 match South. Summaries are 100 and 500. Both the historical and current-territory reports total 600, showing why grand-total reconciliation is insufficient. Check one match per order, then compare grouping against the intended historical policy. Adding the West overlap gives two matches per order and a total of 1200; reject that report until attribution is resolved. The supplied Python/SQLite fixture executes all of these cases and checks the stated results.
Progressive independent practice
Write your analysis before opening each model. Then change the stated fact and revise the reasoning.
Foundation
Why is a primary key on (salesperson_id, valid_from) insufficient to prevent overlapping assignments?
Compare the model reasoning
Two rows can have different starts yet cover the same date. The key prevents duplicate key values, not intersecting time intervals. A row-level ordering check likewise cannot alone compare two history rows.
Changed conditions
The table now has UNIQUE(salesperson_id) instead.
Compare the revised analysis
That prevents multiple history rows entirely, so it cannot represent the required sequential assignments. It avoids overlap by destroying the intended history model.
Application
An order on April 1 matches both North and South because both intervals use inclusive end dates. Propose a correction and a test.
Compare the model reasoning
Adopt a documented half-open convention and use order_date < valid_to for a finite end. Confirm March 31 maps North, April 1 maps South, and each order matches exactly once. Apply the convention consistently to stored values and all consumers.
Changed conditions
Dates are actually timestamps in different time zones.
Compare the revised analysis
The date-only fixture no longer settles the boundary. Define the authoritative time basis and normalize timestamps before comparison. A cast that truncates time may change the assignment and needs its own tested policy.
Transfer
A colleague adds an index, sees a different query plan and declares the historical revenue problem fixed. Evaluate the evidence.
Compare the model reasoning
The index addresses a possible access path, not attribution semantics. Run the unchanged query against the known fixture, check per-order matches and verify North 100/South 500. Then assess performance separately on representative workload. An incorrect query can become faster.
Changed conditions
The indexed query returns the correct groups, but an overnight import introduces overlapping history rows.
Compare the revised analysis
Re-run integrity and cardinality checks after the import. Correctness on yesterday’s fixture does not validate new data. Reject or quarantine ambiguous records under a documented policy, and investigate how the import bypassed temporal controls.