From records to defensible business decisions
Six original connected lessons. Start with cleaning and quality if you are new to data; then statistics, joins, reconciliation and constraints. Estimated planning allowance: 45–75 minutes per lesson, plus Python setup. This is a suggestion, not measured learner time. Prerequisites: basic Python, tables, arithmetic and the linked chapters.
The CSV cleaning fixture and SQL fixture are separate. The SQL examples seed their own three orders; they do not silently import the four formatting-accepted CSV rows. Compare their different contracts before attempting integration.
Download, predict and run
Save all five files into the same folder. Open a terminal in that folder. The workshop runs locally; the website does not execute Python. Use the catalogue attempt checkbox and response area for your own progress.
- records_practice.py
- records_practice_test.py
- records_schema.sql
- practice_orders.csv
- records_expected.json
python3 records_practice.py python3 -m unittest records_practice_test.py
Compare the printed JSON with records_expected.json. There are 22 scenario tests. The expected JSON is a baseline fixture output, not evidence that your modified case is correct. Keep a separate copy when changing data.
SQL joins: preserve the grain
Expected: Naive joined sum 70,000 paise; order sum 60,000; C3 has zero matched orders.
A join combines related records; it does not promise that an amount can safely be summed afterwards. Start with the grain: one row in orders represents one order, whereas one row in payments represents one payment. O1 has two payments, so joining orders directly to payments repeats its order amount twice. The arithmetic is 10,000 + 10,000 + 20,000 + 30,000 = 70,000 paise. The actual order table contains only 60,000 paise. This difference is a reporting error introduced by the query, not new business value.
Read joins() before running the program. Draw three order boxes and connect the four payment boxes to their orders. Count the resulting pairs. Then read the customer LEFT JOIN: C3 has no orders but remains visible. COUNT(o.order_id) returns zero for C3 because there is no matched order ID. COUNT(*) would count the retained customer row and misleadingly show one. COALESCE gives a display total of zero; it does not establish why that customer has no orders.
Do not repair the inflated sum with SUM(DISTINCT amount_paise). Two legitimate orders may have the same amount, and distinct amounts would collapse them. Instead aggregate at the intended grain, or aggregate payments by order before joining. Add a second 10,000-paise order for C2 in a disposable in-memory session. Explain why a distinct-amount strategy now undercounts even though the original fixture seemed to support it.
The sales department owns the order definition, finance owns the recognition policy, and the data team owns the transformation. Their agreement should specify whether the report means booked orders, invoices or recognised revenue. This exercise reports synthetic order amounts only. It excludes tax, cancellation, credit notes, currency conversion and revenue-recognition rules. A correct join is necessary for a dependable report but does not settle these policies.
Foundation: explain the repeated row in plain language. Undergraduate: write the joins and compare counts. Postgraduate: critique the distinct-sum shortcut and document grain. Research: propose a study of how reporting contracts prevent departmental disagreement, including a sampling method and observable error measures. Submit your row diagram, two queries, predicted and actual totals, and a short managerial note explaining the correction.
SQL reconciliation: exceptions before totals
Expected: O1 difference 0; O2 +5,000 paise; O3 −5,000 paise. Net zero hides two exceptions.
Reconciliation asks whether records that should agree actually agree under a stated rule. Here the rule compares each order amount with the sum of its payments. It is not a bank reconciliation or a full accounting control. The fixture includes three orders: O1 is exactly paid, O2 is short by 5,000 paise and O3 is overpaid by 5,000 paise. The combined difference is zero. Reporting only that combined difference would conceal two unresolved cases.
Read reconciliation() and locate its common table expression named paid. This groups multiple payments into one total per order before the join. O1's two payments become 10,000 paise, preserving the order grain. The LEFT JOIN retains an order with no payments. COALESCE treats its absent payment sum as zero for this classroom comparison. It must not be confused with a verified bank balance or confirmation that no unrecorded payment exists elsewhere.
Calculate the four columns by hand: order ID, order amount, paid amount and order minus paid. Label a positive difference as outstanding and a negative difference as excess in this exercise. Never take an absolute value before recording the direction. Finance needs that direction to decide whether to chase a payment or investigate a refund or allocation problem. Customer service should confirm the underlying reference before contacting a customer.
In a disposable session add O4 for C3 at 1,000 paise without a payment. Predict its difference and run the query. Next imagine a genuine payment with a wrong reference. A total may look reasonable while the relationship is wrong. Specify which department can correct that reference, who authorises the change, whose evidence is needed, when the exception escalates and how the revised result is traced. Do not silently edit historical financial records.
Foundation: explain why zero net difference does not mean all orders match. Undergraduate: reproduce the grouped payment query. Postgraduate: design an exception queue with owners, ageing and evidence. Research: propose how to measure the effect of reconciliation timeliness on error recovery without claiming causality from a simple before-and-after average. Submit the three expected rows, the O4 result, an exception register and a correction protocol. Timing differences, settlements, exchange rates and disputed recognition remain outside this fixture.
Database constraints: reject and recover
Expected: Six rule violations rejected; OX rolled back; original three orders retained.
A database constraint expresses a rule the storage engine can check. It is stronger than hoping that every calling program remembers the rule, but it cannot verify every business fact. The classroom schema requires identifiers, nonnegative integer amounts and valid parent references. Open records_schema.sql and identify the primary keys, NOT NULL declarations, CHECK expressions and foreign keys. The script explicitly enables SQLite foreign-key enforcement on its connection and verifies that setting.
Predict six rejected operations before running constraint_demo(): a duplicate order key, an unknown customer, a negative amount, a missing amount, a fractional amount and deletion of a customer referenced by orders. Required fields have explicit NOT NULL declarations. The amount check includes typeof(amount_paise)='integer' because this schema uses SQLite affinity rather than relying on a declaration alone. It checks the stored value's type, not the provenance of the original user input; a numeric string may be converted to an integer by affinity.
Distinguish rejection of a statement from recovery of a multi-statement operation. The demonstration attempts to create order OX and then attach a payment to a nonexistent order. Within the Python connection transaction context, the second insert fails and the first insert rolls back. Confirm that OX is absent afterwards. Without a transaction boundary, a workflow could retain half of the intended business operation. Transaction handling here is local SQLite behaviour, not a guarantee about an external payment service.
The database administrator should implement and monitor the storage contract. Business owners decide which values and relationships are legitimate. An unknown customer may signal a typo, a delayed master-data update or a real missing customer. A constraint should block the unsupported write while humans investigate; it should not automatically invent a parent record. Explain why disabling foreign keys to make the error disappear removes the protection instead of resolving the cause.
Foundation: describe one rejected write. Undergraduate: map each rejection to its rule. Postgraduate: design an authorised correction process with replay and audit evidence. Research: compare constraint violations and business-rule violations using a defensible taxonomy and a defined observation period. Submit your rule table, rejection log, rollback proof and one example of a believable but incorrect value the database would accept. Identity, authentication, concurrency, backups and distributed transactions require separate study.
Python cleaning: preserve correction evidence
Expected: Four format-accepted records; one identical replay, one conflict, one missing amount and one negative amount.
Cleaning is an explicit transformation contract, not permission to erase inconvenient observations. The CSV fixture has eight source rows. Four pass its formatting and duplicate rules; four are classified as issues. Open the file and predict each row's treatment before running read_orders(). Whitespace is stripped from identifiers and amount text. Amounts must be nonnegative ASCII integer paise within SQLite's signed integer range. Blank, fractional, negative and non-finite representations are rejected rather than guessed.
The first valid occurrence of an order ID establishes the accepted record in this bounded exercise. A later identical occurrence is marked as an identical replay and does not increase sales. A later occurrence with different content is marked as a conflicting replay; the original remains accepted and the conflict needs human resolution. This is a classroom first-valid policy, not a universal rule for event processing. In a real correction workflow a later authorised revision might legitimately replace an earlier value.
O2 appears three times. Its first amount is 20,000 paise, its second repeats that amount, and its third says 25,000 paise. Explain why summing all three or keeping the last automatically would conceal a decision about source authority. O4 has a missing amount; treating that as zero would manufacture information. O5 has a negative amount; our contract rejects it because returns need a separate representation. A retailer that encodes refunds as negative amounts would need a different documented contract.
Keep a copy of the synthetic file before experimenting. Change one field, predict the accepted records and issue reason, then run the function again. The supplied program reads the file and prints results without rewriting it. Issue records retain source line numbers to support investigation, although they are not a complete durable audit log. Record the original input, rule version, changed copy and responsible reviewer in your portfolio.
Foundation: explain missing versus zero. Undergraduate: trace the validation branches. Postgraduate: compare first-valid, latest-authorised and quarantine-all conflict policies. Research: define precision and recall for a proposed cleaning policy using independently labelled errors. Operations explains the transaction, finance defines allowed amounts, IT maintains the parser and a steward authorises corrections. Submit an eight-row classification table and a policy memo stating whose judgement is needed before publication.
Descriptive statistics: name the population
Expected: n=4; total 100,000 paise; mean/median 25,000; sample deviation ≈12,909.9445 paise.
A mean describes selected values; it does not validate the selection. The formatting-accepted order amounts are 10,000, 20,000, 30,000 and 40,000 paise. Their count is four, total 100,000, mean 25,000 and median 25,000. The sample standard deviation is approximately 12,909.9445 paise. Convert units carefully: the mean is INR 250, not INR 25,000. The script retains paise throughout and labels every result.
Calculate the mean as total divided by count. For the median, sort the four values and average the two middle values. For the sample standard deviation, deviations from 25,000 are −15,000, −5,000, 5,000 and 15,000. Their squared sum is 500,000,000; divide by n−1, which is three, and take the square root. Explain that this sample convention differs from dividing by n for the population standard deviation. The fixture does not establish that these observations are a random sample from any wider population.
There is a deliberate warning: O6 references unknown customer C9. The values pass formatting checks but are not all ready for a released customer-linked report. Filtering to the three known-customer rows changes the mean to 20,000 paise. Neither result is universally correct; each answers a different, explicitly bounded question. Publish the inclusion rule, rejected count and unresolved references alongside the statistic. Do not call this a cleaned company-wide average.
The empty-record case returns no mean, median or sample deviation. A singleton has a mean and median but no sample standard deviation. Missing results are represented as None, not zero. Test these cases and explain what a dashboard should display. A zero variation claim would mean observed equality, whereas an undefined sample statistic means insufficient observations. An attractive chart should not blur that distinction.
Foundation: interpret units and central tendency. Undergraduate: reproduce all calculations. Postgraduate: examine selection bias, skew and whether average order size serves the decision. Research: propose a sampling frame and uncertainty analysis before generalising beyond the fixture. Sales may ask about typical orders, finance about value concentration and operations about workload, which may correlate poorly with order amount. Submit hand calculations, both inclusion policies, the empty and singleton outputs and a short answer to which statistic serves which department.
Data-quality checks: release is a decision
Expected: Four formatting issues and orphan O6; release_ready=false. Clean known-customer input passes the stated gate.
Data quality involves fitness for a named purpose. The cleaning lesson verifies formatting and replay rules; this lesson adds a referential check against the supplied customer set. O6 names C9, which does not appear among C1, C2 and C3. It remains a format-accepted record but is flagged as an unknown-customer order. Separating these checks prevents a parser success from being mistaken for complete business validity.
Read quality() and identify its outputs: accepted-format count, issue count, unknown-customer order IDs, counts by issue reason and a conservative release flag. The supplied fixture has four format-accepted rows, four issue rows and one unknown-customer order. release_ready is false. This flag means the fixture has unresolved issues under its stated policy. It does not mean that all issues have equal severity or that every organisation must stop every report for the same reason.
Make a quality register with one row per issue type. For an identical replay, ask whether the ingestion mechanism retried a legitimate event. For a conflict, ask whose source has authority. For missing and negative amounts, ask what information the source intended. For an unknown customer, ask whether master data is late or the reference is wrong. Assign an owner, evidence requirement, correction deadline and escalation route. Human consultation is essential when the record's meaning is uncertain.
Modify a disposable copy so the input contains only O1 for C1 with 100 paise and no issues. The flag becomes true. Now use O1 for C9 with the same valid amount. With no formatting issues, the flag still becomes false because of the unknown customer. A clean technical pipeline can pass believable but false information if the reference list or source is wrong. State explicitly that truth, completeness, freshness and authorisation are not fully checked by this function.
Foundation: explain quality in relation to use. Undergraduate: trace format and reference checks separately. Postgraduate: design severity thresholds, accountable overrides and monitoring without concealing unresolved exceptions. Research: develop a method to evaluate whether quality rules reduce decision errors rather than merely raise a pass rate. Submit a quality register, changed-case outputs and a release recommendation addressed jointly to a business owner and data steward. Security, privacy, real personal data, automated remediation and production observability are outside this synthetic exercise.
Free primary learning resources
- SQLite SELECT and join processing — query behaviour and joins.
- SQLite CREATE TABLE — storage rules and constraint semantics.
- SQLite foreign-key support — enforcement, parent/child rules and limitations.
- Python statistics — mean, median and sample variation.
- Python CSV — structured file reading.
- Python sqlite3 — connection and transaction behaviour.
The first four references were reviewed on 5 October 2026. CSV and sqlite3 links are further official reading pointers, not separately audited course syllabi. These public documentation links do not promise a certificate or live webinar.
Portfolio checkpoint
For each lesson retain: input contract, prediction, output, changed case, issue owner, correction authority and limitation. Ask Who owns the decision, Whom it affects, Whose evidence authorises a correction, What is measured, Where the record originated, When it was valid, Why it differs, Which rule applies and How to test the correction. A successful execution is practice evidence, not proof of mastery.