Lawfare Group → Knowledge Institute → Lawfare Academy
← Data Management and SQL for Business
Unit 6
Business queries and validation
Learning objectives
- Explain business queries and validation in your own words.
- Apply the principle to the worked business case.
- Evaluate the answer and identify an assumption that could change it.
Business queries and validation
Write the business question first, specify eligible records and dates, then reconcile query totals to trusted records. Test small examples with known answers. A query that runs successfully can still compute the wrong quantity.
Worked example
A revenue report excludes canceled invoices, uses the intended service dates, and reconciles totals to the ledger.
Current on-site learning
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.
Work through the reasoning
Define the business workflow, data, users, system boundary, and failure consequences. For this unit, connect the explanation of business queries and validation to the worked example before answering the practice question.
Check the limits
Test a representative case and identify controls, exceptions, recovery, and the accountable human owner. If the source model and the practical example use different assumptions, state the difference rather than applying the formula or rule mechanically.
Apply it independently
What establishes analytical correctness? Write an answer before opening the model response. Show the calculation or explain the causal or logical steps. Change one material assumption and say whether your conclusion changes. This practice is optional; you can read every part of the course without submitting work.
Original Academy expansion: validate a business report as a chain of claims
A useful business query starts with a written report contract. Define the population, grain, measures, as-of time, inclusion rules, expected treatment of missing data, and reconciliation checks. For the laboratory report, return one row per job with customer, billed cents, paid cents, and open cents. Include every job, even one without payments. Exclude no status implicitly. Call the balance a simplified operational receivable because the fixture omits taxes, credits, write-offs, and invoice-recognition policies.
Worked investigation: an inspectable receivables query
The lab's billed CTE groups job_lines by job_id and sums quantity times unit_cents. Its paid CTE groups payments by job_id and sums amount_cents. The final SELECT starts from jobs, joins customers on customer_id, and LEFT JOINs each aggregate. COALESCE turns no line or payment aggregate into zero for this fixture's explicitly complete event population. Open cents equals billed cents minus paid cents. ORDER BY job_id makes output stable for inspection; row order without an ORDER BY is not promised.
The expected rows are job 101 with billed $250, paid $100, open $150; job 102 with billed $80, paid $40, open $40; and job 103 with billed $400, paid $250, open $150. Totals are billed $730, paid $390, and open $340. Independently sum the base child tables and compare these totals. Matching grand totals is necessary but not sufficient: two job-level mistakes can cancel. Also compare each known job, assert unique job_id in the output, and check that all intended jobs appear.
Build fixtures that defeat plausible wrong queries. This one contains multiple lines and payments on the same job, equal-valued legitimate lines, a customer with no jobs, and a job with a partial payment. Add cases with no payments, no lines, an attempted orphan reference, duplicate external events, and a boundary date. A test suite filled only with one-line fully paid jobs would let many defective queries pass. Test design begins with the failure modes, not with copying the implementation's expressions into expected values.
Window functions answer a different class of question from grouping. SUM(amount_cents) OVER (PARTITION BY job_id ORDER BY payment_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) can display each payment alongside a running job total without collapsing rows. Choose a deterministic ordering appropriate to the business. payment_id is used in the fixture for a simple reproducible sequence; real posting order may require a timestamp and a tie-breaker. A cumulative total by arbitrary identifier may not describe the historical balance at each business moment.
Indexes support access paths but do not change the promised result relation. A selective filter or join can benefit from an index whose leading columns match the access pattern, while inserts and updates incur maintenance costs. Use EXPLAIN QUERY PLAN in SQLite to inspect a representative workload, then measure realistic data volumes. A fast query returning inflated revenue remains wrong. An index on every column is not a substitute for designing the schema, report, and workload together.
Protect the result's meaning when the source changes. A newly added refund type, multi-job allocation, or currency column may invalidate an old SUM. Establish a data contract, source-completeness checks, and a revision record. If two currencies appear, adding their raw cents is not a valid financial total. If late postings arrive, state whether prior reports restate or remain snapshots. A dashboard should reveal its as-of time and measure definition, because an attractive chart cannot communicate assumptions the system never recorded.
Progressive practice
- Foundation: reproduce all three job rows and their grand totals from the fixture.
- Application: add an unpaid $50 job for customer 3 and state the expected new totals before running the query.
- Transfer: add a second $40 payment to job 102. Explain why the job count remains unchanged and calculate the new open total.
- Synthesis: design a test that distinguishes a correct report from both the direct-child-join query and the SUM(DISTINCT amount) query.
Worked reasoning for the practice
The starting totals are $730 billed, $390 paid, and $340 open. An unpaid $50 job gives $780, $390, and $390, with four job rows. Starting from the original fixture instead, adding a second $40 receipt to job 102 gives $730 billed, $430 paid, and $300 open, still three job rows. Keep the multiple-child job 101 to expose fanout and the two equal-priced lines on job 103 to expose DISTINCT. Expected results should come from independently specified event facts, not from another version of the same faulty join.
Reading alignment for this expansion
The earlier introductory links remain background reading. Use the complete current on-site studios; publisher links are optional provenance. The original Academy worked records above are not quotations from those sources.
Extended text lesson
Continue with A faster report must still describe one coherent database state for the full worked case, source readings and optional progressive practice.
Extended text lesson
Continue with SQL: reconcile the order report and an idempotent correction for the full worked case, source readings and optional progressive practice.
Complete current conceptual preparation
Validate the report, the analytical dataset and the system that delivers them
A report is an executable chain of claims
Write the eligible population, output grain, measures, source cutoff, status policy, missingness policy and currency before optimizing a query. The preserved Cedar job report has three rows with billed 730,paid 390,open 340 dollars; its counterexamples expose fan-out and equal-priced legitimate lines. The separate preserved paid-order cumulative dossier has billed 6500,settled 6500,posted refunds 800 and net billed 5700 cents, excluding draft 700 and pending 500 under explicit policies. Do not combine those independent fixtures or call either a universal revenue-recognition rule.
Validation needs both totals and keyed facts. Check unique output keys, intended parent coverage, unmatched relationships, duplicate input identities, unknown amounts and boundary timestamps. Compare source-to-target facts in both directions and inspect multiplicity. A correct grand total can hide offsetting account errors. An optimization is acceptable only if the complete promised result remains unchanged; a changed execution plan is not a correctness proof. The preserved 10,000-event and WAL examples separate semantics, access strategy and snapshot visibility without promising universal speed.
Prepare data for learning without leaking the answer
Big-data problems concern volume, arrival speed, varied representations, reliability and practical usefulness, not a magic row-count threshold. A small sensitive dataset can be harder to govern than a large public one. Integration aligns identities, units and timing across sources; it must preserve uncertainty about unresolved matches. Batch pipelines process bounded groups, while streams process arriving events with policies for ordering, late data, replay and failure recovery. A streaming output is not automatically complete for an event-time period just because no new row arrived in the last minute.
Supervised learning uses labeled examples to predict a target; classification predicts categories or probabilities, regression predicts a quantitative outcome. Unsupervised methods, such as clustering, seek structure without the same provided outcome labels. A clustering label is not ground truth or a causal explanation. A shallow model may use explicit features and a relatively simple decision structure, such as linear/logistic models or trees. A deep neural model learns multiple layers of representation through fitted parameters; image, text and sequence applications may benefit when appropriate data and compute exist. Complexity does not remove the need for quality, an admissible target or honest validation.
Tools operate at different layers. SQL constructs eligible cohorts and features; Python/R libraries implement transformations and model estimation; distributed query engines or massively parallel processing(MPP) divide work across workers; deep-learning frameworks support tensor operations, automatic differentiation and accelerated training. Naming a tool does not make a result verified. MPP can distribute table partitions and partial aggregates, then combine results. Data skew, network shuffles, coordination and failure retries limit speedup. If 80%of a workload is parallelizable and four workers are otherwise ideal, Amdahl's simplified speedup is 1/(.2+.8/4)=2.5, not 4. That model omits real overhead and is an upper-bound reasoning exercise under its assumptions.
Feature construction needs a decision-time contract. To predict next-month late payment at month-end, a feature called eventual_collection_date contains future information and must not enter a historical forecast. Split by time and, where the target is new accounts, by account; repeated rows from the same entity can otherwise leak identity-specific patterns. Fit imputation, category encodings and scaling only within training. Preserve labels, feature definitions, source versions and the model version. Evaluate against a simple admissible baseline on the same targets, not against a deliberately weak comparator with less information.
Worked classification and changed threshold
Use a separate synthetic frozen holdout of 100 invoices:20 ultimatelylate and 80 on time. A fixed threshold flags 25:15 true late and 10 false alarms. The remaining 75 contain 5 missed late and 70 true negatives. Accuracy 85%,precision 15/25=60%,recall 15/20=75%,specificity 70/80=87.5%. A never-late baseline has 80%accuracy but zero recall. These are observed holdout proportions, not guaranteed population rates. Report the selection and threshold process, sample size and costs.
Suppose a missed late invoice costs 100 units and a false alarm costs 10. This threshold has loss 5*100+10*10=600. Another frozen threshold catches 18 of 20 late but falsely flags 25 of 80 on-time invoices, giving loss 2*100+25*10=450 and accuracy 73%. Lower accuracy can accompany lower declared loss. If costs become 20 for a miss and 20 for a false alarm, losses are 300 and 540, reversing the preference. Declare costs before choosing a winner, and retain an independent evaluation after threshold selection. If all thresholds were selected using this holdout, call it development evidence rather than untouched final testing.
Informatics connects users, workflow and information
Informatics examines how people and technical systems collect, interpret and use information in a domain. A correct query that staff cannot understand can produce unsafe workflow decisions; a helpful interface built on incomplete records can mislead just as seriously. For a collections screen, show the measure's unit, cutoff, unresolved amounts, evidence and authorized next action. Distinguish a model flag from a verified late payment, and give a way to inspect and correct source errors. The user's role, decision deadline and ability to contest a record are design inputs, not cosmetic additions after coding.
An information-system lifecycle includes understanding the problem and stakeholders, feasibility and requirements, design, implementation, validation, deployment, operation/change and eventual retirement or migration. A health, sports or financial application uses different domain vocabularies and consequences even if all store tables. Text instruction and synthetic tests do not establish clinical competency, regulatory approval or authority over real people. This course's examples support business-data reasoning; they do not make automated eligibility or care decisions.
Engineer a small reporting service as a maintained system
Software engineering applies organized design, construction, evaluation and maintenance to a useful system. Requirements include functional behavior(one row per eligible order, an authorized refund operation) and quality constraints(correctness, availability, security, accessibility, latency and recoverability). Make each testable. 'Fast and secure' is not an acceptance criterion. 'A reporting identity cannot update source orders' and 'the report retains accounts without payments and exposes unknown amounts' have observable consequences. Include data contracts, interfaces and external dependencies in the design.
A layered design can separate ingestion validation, persistence/transaction operations, report queries, service authorization and presentation. A repository abstraction can isolate data-access details, while an outbox pattern coordinates committed events with later message delivery. Patterns are reusable structures for recurring problems, not proof that every project needs a framework. Keep responsibilities clear enough to test failure boundaries. Refactoring changes internal structure while intending to preserve externally promised behavior; a change from current-price to historical-price reporting is a semantic correction and must be described as such, even if it accompanies refactoring.
Process choice depends on risk and feedback. A staged plan can make stable interfaces and formal approvals explicit; an iterative or agile process delivers small tested increments and revises requirements through feedback. Neither means skipping documentation, security or preservation. A risk-driven spiral emphasizes resolving major uncertainties through successive cycles. Prototypes can test workflow or feasibility but require a clear boundary before becoming relied-upon production systems. Source control, code review, automated builds, dependency tracking and issue histories provide traceability across methods. Continuous delivery prepares verified changes for release; it is not permission to deploy every experiment without the relevant authority.
Testing has complementary scopes. Unit tests check an isolated transformation; integration tests exercise actual interfaces/transactions; system tests verify the connected workflow; user acceptance assesses whether real users can accomplish the intended task. Static analysis and review inspect code without running it. Black-box tests focus on specified behavior; white-box tests consider implementation paths. Boundary, property-based and adversarial fixtures can expose errors that ordinary examples miss. Regression tests protect earlier promises. Code coverage records which code was exercised, not whether expectations were correct. Agent-run tests are not observed human learner or subject review.
Worked requirements-to-release ledger
For the preserved paid-order case, requirement R 1 is one row per paid order with billed 6500,settled 6500,refund 800 and net 5700; R 2 excludes draft 700 and pending 500 but keeps them in exception checks; R 3 applies refund command R 3=400 exactly once and rejects a changed payload; R 4 preserves orders, line prices and settled payments; R 5 exposes a consistent read cutoff. Test R 1 with independent event arithmetic and exact rows, R 2 with status boundaries, R 3 with replay/conflict/over-limit/failure injection, R 4 with before/after keyed comparisons and R 5 with the documented snapshot fixture.
A release ledger connects each requirement to design, test evidence, method/schema version, review status, rollback strategy and monitoring. A rollback to an old application may not undo a destructive schema migration; plan backward/forward compatibility and preserve recoverable data. A canary or limited rollout can reduce exposure while monitoring known invariants, but a passing small slice does not prove all workloads. Keep an incident and correction record. The actual Academy learner database is outside every laboratory in this course.
Reuse includes libraries, modules, services and tested domain components. Review license, provenance, version, maintenance, interfaces and security exposure before adoption. Free/open-source availability does not mean no obligations or no risk. A permissive library and a reciprocal license can impose different conditions; the concrete license text and intended distribution matter. This lesson makes no specific legal conclusion. Professional ethics includes accurate evidence claims, respect for privacy and accessibility, reporting known limits and avoiding deceptive metrics. AI-assisted generation can speed drafting or code suggestions, but output still requires source checking, tests and accountable review; a confident generated query can duplicate money.
Optional progressive practice
Guided model: test a learning-data claim
The first holdout hasTP 15,FP 10,FN 5,TN 70:accuracy 85%,precision 60%,recall 75%,specificity 87.5%. Declared miss 100/false-alarm 10 loss 600. Changed fact: the alternative frozen threshold givesTP 18,FP 25,FN 2,TN 55. Accuracy 73%butloss 450. Name the cost target and threshold-selection history rather than declaring the larger accuracy universally better.
Independent model: scale and leakage are distinct
The simplified 80%-parallel/four-worker speedup is 2.5. It says nothing about whether an eventual collection-date feature was available at issue time. Changed fact: a thousand workers make the leaked model run faster. The evidence remains invalid for the historical forecast; remove future information and reconstruct the admissible evaluation before interpreting speed or accuracy.
Transfer model: passing tests is not human acceptance
Exact SQL and transaction fixtures can establish their own stated results, while staff usability and independent academic review remain separate. Changed fact: a user observes that a zero and an unknown amount look identical. Treat that as a real presentation requirement defect, preserve the old evidence and revise display and tests. Do not call a new test a retroactive human review of all courses.
Unit rubric: 20 points
Four points each for exact report/lineage/snapshot validation; learning-data eligibility and threshold metrics; informatics and testable requirements; connected design/process/testing/release preservation; and ethical changed-fact reasoning. Complete model retains the original 6500/6500/800/5700 report, post-refund 1200/5300, all replay and historical-price boundaries, and separately calculates 85%/600 versus 73%/450 for the independent classifier. It declines both false software and false human-review claims.
Optional source summaries: OpenStax's learning-data section and informatics section were read for their data/pipeline and human-system scope. Its software fundamentals, process and testing/reuse/ethics topics informed the topic boundaries. The methods, classifier, requirements ledger and complete models above are original on-site teaching, not assigned external chapters or copied textbook prose.
Developed study chapters
Original explanation, worked analysis and progressive optional practice.
Apply the idea
A revenue report excludes canceled invoices, uses the intended service dates, and reconciles totals to the ledger.
What establishes analytical correctness? Explain your reasoning, then identify one changed fact that could alter the conclusion.
Expanded transfer investigation: Which fixture combination distinguishes the correct query from both fanout and SUM(DISTINCT) errors?
Show the calculation or argument, identify the information available at the decision time, and state which assumption supports your conclusion. The four progressive tasks in the Learn stage provide additional practice.
Read the worked reasoning
Correct definitions and reconciliation. Technical execution and business validity require separate checks. In an independent response, state the given facts, identify the governing relationship, work through the calculation or comparison, and distinguish the conclusion from assumptions that still need evidence.
Expanded transfer reasoning: The two cases expose different plausible wrong implementations.
Progressive practice reasoning: The starting totals are $730 billed, $390 paid, and $340 open. An unpaid $50 job gives $780, $390, and $390, with four job rows. Starting from the original fixture instead, adding a second $40 receipt to job 102 gives $730 billed, $430 paid, and $300 open, still three job rows. Keep the multiple-child job 101 to expose fanout and the two equal-priced lines on job 103 to expose DISTINCT. Expected results should come from independently specified event facts, not from another version of the same faulty join.
Check understanding
The fixture has billed $730 and paid $390. What is its simplified operational open balance?
- $730
Feedback
Incorrect. This ignores the payments.
- $340
Feedback
Correct. Open equals billed minus paid under the fixture's stated omissions.
- $1,120
Feedback
Incorrect. This adds rather than subtracts receipts.
Further reading
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.
- Complete on-site teaching — Validate the report, the analytical dataset and the system that delivers them
- SQLite — SELECT
- SQLite — Transactions
- Academy — Runnable business data investigations
- Introduction to Computer Science — 8.6 Data Management for Shallow and Deep Learning Applications
- Introduction to Computer Science — 8.7 Informatics and Data Management
- Introduction to Computer Science — 9.1 Software Engineering Fundamentals
- Introduction to Computer Science — 9.2 Software Engineering Process
- Introduction to Computer Science — 9.3 Special Topics
- A faster report must still describe one coherent database state
- SQL: reconcile the order report and an idempotent correction