Data Management and SQL for Business — Expanded Original Study
Open this course and its original lessons. This companion contains the same new teaching as the course reader; it is not additional material for word counts.
- Data models and business meaning
- Keys and relational integrity
- Filtering and aggregation
- Joins and duplicate counting
- Transactions and controls
- Business queries and validation
Unit 1 · Data models and business meaning
Original Academy expansion: make the business meaning explicit
A database is a set of claims about a business, expressed in a structure that determines which questions can be answered reliably. Start with the grain: what does one row represent? A customer row might represent a billing account, a person, or a household. A job row might represent an appointment, a work order, or an entire contract. Those are different entities. A query cannot repair an ambiguous definition after the fact. Write a short data dictionary stating each table's grain, identifier, important attributes, and time interpretation.
For the fictional Cedar Service laboratory, customers represent billing accounts, jobs represent work orders, job_lines represent separately priced lines on a work order, and payments represent payment events allocated to one work order. One customer can have several jobs. One job can have several lines and several payments. This structure deliberately separates two one-to-many relationships that later create a common double-counting error. Every amount in the laboratory is an integer number of cents. The examples omit tax, refunds, credit notes, and multi-invoice allocations so the accounting assumptions remain explicit.
An entity has identity even when its descriptive fields change. A customer changing a telephone number should not become a new customer merely because the phone number was used as a key. A natural key comes from the business domain, such as an externally guaranteed account code. A surrogate key is introduced as an identifier, such as customer_id. A surrogate key does not remove the need to enforce real business uniqueness where required. If two accounts must not share the same external code, that rule requires its own constraint.
Separate current state from historical events. A customer's current address cannot reconstruct the address used for an invoice two years ago unless the relevant history was retained. A job's current status cannot reveal every prior status transition unless transitions were recorded. Sometimes a document should preserve a snapshot even when a customer master record changes. Other questions need a valid-from/valid-to history. Decide what historical question must be supported before overwriting a field.
Normalization is a method of reducing harmful dependencies, not a command to maximize the number of tables. If every job repeats the customer's current contact address, changing that address may require many updates and leave inconsistent copies. Move attributes dependent on the customer to the customer table, while retaining genuinely document-specific facts on the document. A fact such as the agreed price on a historical job line should usually remain on that line; changing today's price list should not rewrite what the customer agreed to pay earlier.
Worked investigation: a deceptively convenient spreadsheet
Imagine one sheet with customer_name, customer_phone, job_id, job_status, line_description, line_price, payment_date, and payment_amount. Job 101 has two price lines and two payments. Representing all combinations can require four rows. The same line price and payment can appear repeatedly. Summing either column now risks inflating totals. Keeping one row per job instead forces lists of lines or payments into cells, making individual constraints and queries difficult. The issue is a mismatch between several grains, not simply an untidy spreadsheet.
Use four tables instead. customers stores account identity, jobs stores the work-order relationship and status, job_lines stores each priced line, and payments stores each receipt. Foreign keys express the allowed relationships. Queries can then aggregate each grain before combining results. If one payment can cover several jobs, add a payment header and allocation table rather than pretending the one-job payment model still applies. Schema design must change when the business relationship changes.
NULL represents missing or inapplicable information under a chosen convention. It is not automatically zero or an empty string. A NULL completion date might mean unfinished, unknown, or not applicable; using one value for three meanings may need an accompanying status or reason field. In SQL, comparisons involving NULL generally yield UNKNOWN rather than TRUE or FALSE. The WHERE clause retains TRUE rows. Therefore completion_date = NULL is not the test for missing dates; use IS NULL. Business semantics come first, followed by correct SQL mechanics.
Progressive practice
- Foundation: state the grain and primary key for customers, jobs, job_lines, and payments.
- Application: explain where the agreed historical line price belongs when the current price list changes.
- Transfer: one receipt pays two jobs. Describe the additional relationship needed without duplicating the receipt.
- Critique: a report labels every NULL completion date as a late job. Identify at least two alternative meanings that must be checked.
Worked reasoning for the practice
The grains are one billing account, one work order, one priced work-order line, and one payment event allocated to a work order. Their identifiers are customer_id, job_id, line_id, and payment_id. Historical agreed price belongs with the historical line, while current list price is a different fact. For shared receipts, retain a single payment event and introduce allocations with their own allocation amounts and job references. A missing completion date could identify unfinished work, an unrecorded date, or a canceled job. A late-work query needs a due date, an as-of date, and status rules in addition to missingness.
Subject-matched external readings
Unit 2 · Keys and relational integrity
Original Academy expansion: keys, dependencies and enforceable integrity
A primary key uniquely identifies a row and must not be NULL. A foreign key constrains a child reference to match an allowed parent key, subject to the declared treatment of NULL. A uniqueness constraint enforces a candidate key. A CHECK constraint enforces a row-level condition expressible in that database's constraint language. These rules prevent particular invalid states; none proves that a real-world event was measured correctly. A payment can satisfy every constraint and still be entered against the wrong valid job.
In SQLite, enable foreign-key enforcement for the connection before starting the laboratory transaction: PRAGMA foreign_keys = ON. Verify the setting. Defining REFERENCES clauses while enforcement is disabled does not supply the protection assumed in these exercises. Engine configuration is part of the integrity design. Other database products have different defaults and features, so identify the engine and version when moving code between systems.
Consider jobs(job_id, customer_id, status, opened_date). job_id determines the remaining job attributes. customer_id determines customer-level attributes stored in customers, rather than in jobs. A functional dependency concerns the meaning of the data, not merely a pattern in a small sample. Five observed customers having different names does not make name a reliable key. Two different accounts can legitimately share a name, and one account can change its name.
Worked investigation: defend against four invalid states
The laboratory schema declares jobs.customer_id as NOT NULL and REFERENCES customers(customer_id). Attempting to insert a job for customer 999 fails when 999 is absent. Attempting to insert an existing job_id fails the primary-key rule. A status outside the declared set fails the CHECK rule. A line with negative unit_cents fails the nonnegative-price rule. Test all four deliberately in a disposable database. Merely reading the CREATE TABLE statement is weaker evidence than seeing the invalid states rejected.
A UNIQUE constraint can behave differently from an intuitive business rule when NULL values are involved. SQLite permits multiple NULL values in a UNIQUE column. If every customer must have an external_code and it must be unique, use both NOT NULL and UNIQUE. Do not rely on a generic phrase such as unique code without specifying missing-value behavior. Case and whitespace rules also matter: AB12, ab12, and AB12 followed by a space may represent the same business identifier while being different stored strings unless normalization or collation rules address the issue.
Referential actions need policy decisions. Deleting a customer who has historical jobs should not casually erase those jobs. The laboratory leaves deletion restricted by default. Some systems require archival or a separate inactive status. Cascading deletion is appropriate only when the child facts should cease to exist with the parent, and retention requirements have been considered. A convenient cleanup command is not a substitute for deciding what a historical record means.
Row-level checks have limits. A payment's amount_cents > 0 check rejects nonpositive receipts in this simplified model, but it does not ensure that total allocations across rows equal the payment header. A CHECK on one row normally cannot enforce every aggregate invariant across several rows. Such rules may require transaction logic, triggers, a different representation, and reconciliation. State which layer enforces each rule and test the failure path. An interface that checks a value can be bypassed by another writer unless the trusted data layer enforces it too.
Progressive practice
- Foundation: distinguish a primary key from a foreign key using job_id and customer_id.
- Application: design the constraints for a required unique external account code.
- Transfer: explain why nonnegative line amounts do not guarantee a correct invoice total.
- Critique: a team enables cascading customer deletion to simplify test cleanup. Explain the consequence for real historical jobs and propose a safer test practice.
Worked reasoning for the practice
job_id distinguishes jobs; customer_id refers to a permitted account, and it can repeat across jobs. The external code needs NOT NULL and UNIQUE, plus an explicit normalization policy. Correct totals also depend on quantities, included statuses, taxes or credits if supported, and preventing join fanout. Use isolated fixture databases for destructive tests. In a production design, select deletion, archival, or retention behavior intentionally. The correct default is not determined by which command makes a developer's cleanup easiest.
Subject-matched external readings
Unit 3 · Filtering and aggregation
Original Academy expansion: filtering, grouping and NULL
SQL is declarative: specify the result relation, while the engine chooses an execution strategy. A useful conceptual order for a SELECT is FROM and joins, WHERE, GROUP BY, HAVING, SELECT expressions, and ORDER BY. This is a reasoning aid, not a statement that the engine physically executes each step in that order. The optimizer can transform operations while preserving the query's semantics.
WHERE filters input rows before aggregation. HAVING filters groups after aggregation. If the question is which customers have at least two completed jobs, first restrict jobs to completed status, then group by customer_id, then apply HAVING COUNT(*) >= 2. Filtering completed status after counting all jobs answers a different question. A query should be explained in terms of the business population it includes, not only its syntax.
COUNT(*) counts rows. COUNT(column) counts non-NULL values of that expression. SUM and AVG generally ignore NULL inputs; in SQLite SUM over no non-NULL values returns NULL. Whether to replace that with zero is a business decision. No payment events for a job can reasonably be displayed as zero paid after a LEFT JOIN and COALESCE. An unknown measurement should not automatically be converted into a true zero and averaged as though it were observed.
Worked investigation: receipt totals with an explicit population
The lab has customers 1, 2, and 3. Customer 1 has jobs 101 and 102; customer 2 has job 103; customer 3 has no jobs. Job 101 has $100 in payments, job 102 has $40, and job 103 has $250. A query beginning from payments and joining jobs returns customers 1 and 2 with paid totals $140 and $250. It does not include customer 3. If the report promises every account, begin from customers and LEFT JOIN a customer-level receipt aggregate. Then customer 3 can appear with a displayed zero and an explicit no-receipts meaning.
Aggregates need consistent units and denominators. AVG(payment amount) calculates mean payment-event size, not mean total paid per job or mean lifetime customer receipts. In the fixture, payment events are $60, $40, $40, and $250. Their average is $97.50. Paid totals per job are $100, $40, and $250, averaging $130. These both are correct for their grains. Neither is automatically the answer to average customer value. Define the unit of analysis before choosing the aggregation.
Dates need similarly explicit boundaries. For a month, a half-open interval date >= month_start AND date < next_month_start is often easier to reason about than an inclusive end-of-month timestamp. If times are stored, a comparison to midnight on the final date can exclude most of that day. Time zones, daylight-saving transitions, and late-arriving records matter in real systems. The laboratory uses ISO-formatted date-only text, so lexical date ordering matches chronology for the fixed format. Do not generalize that assumption to mixed formats or arbitrary timestamp strings.
SQLite accepts some aggregate queries that other engines reject, including bare nonaggregated columns outside GROUP BY. Do not treat acceptance as correctness. A query selecting customer_id, job_id, and SUM(total) grouped only by customer_id does not generally identify which job_id the sum belongs to. Name the desired result grain and aggregate or group every selected field consistently. If a representative row is needed, specify its selection rule rather than relying on an arbitrary engine choice.
Progressive practice
- Foundation: explain why COUNT(*) and COUNT(completion_date) may differ.
- Application: calculate the fixture's average payment-event amount and average paid amount per job.
- Transfer: specify how to include customers without jobs in a receipt report while distinguishing no events from unknown data.
- Critique: explain why a query that groups by customer but selects an unrelated job_id can give a misleading result even if SQLite runs it.
Worked reasoning for the practice
Rows with NULL completion dates count under COUNT(*) but not COUNT(completion_date). The four payments total $390, so their mean is $97.50; the three job totals also sum to $390, so their mean is $130. Start a complete-account report from customers, attach a separately aggregated receipt relation with a LEFT JOIN, and label any COALESCE-to-zero convention. If ingestion is incomplete, add an explicit data-completeness condition; zero events in an incomplete feed cannot establish zero receipts. An ungrouped job_id lacks a defined relationship to the customer-level aggregate and should be removed or selected by a stated rule.
Subject-matched external readings
- SQLite — SELECT — Selection, grouping, joins, NULL-containing result populations, and aggregate-query behavior.
Unit 4 · Joins and duplicate counting
Original Academy expansion: joins and the multiplication of facts
An inner join returns matching combinations. A left join retains every left row and supplies NULLs when no right match exists. Neither join knows which monetary totals should remain additive. If a job has two lines and two payments, joining both child tables to the job produces four combinations. Each line repeats once for each payment, and each payment repeats once for each line. This is fanout. The query can look reasonable, satisfy all referential constraints, and still double both totals.
Worked investigation: diagnose a false receivable
Job 101 has two lines worth $100 and $150 and two payments worth $60 and $40. The real billed total is $250, the paid total is $100, and the outstanding amount in this simplified fixture is $150. A direct join of jobs to job_lines to payments produces four rows: line 100 with payment 60, line 100 with payment 40, line 150 with payment 60, and line 150 with payment 40. Summing joined line amounts gives $500; summing joined payments gives $200. The resulting balance is $300, twice the real balance.
The repair is to aggregate each child independently to the intended common grain, one row per job, then join those aggregates to jobs. The laboratory's correct query uses one CTE for billed cents and another for paid cents. A CTE names a subquery and makes its grain inspectable; it does not inherently prevent duplicates. The protection comes from GROUP BY job_id in each child aggregate and the uniqueness of the job relation being joined. Explain that logic before trusting the query.
SUM(DISTINCT amount) is usually the wrong repair. Job 103 deliberately has two valid lines of $200 each. SUM(DISTINCT line amount) would return $200 instead of the correct $400. DISTINCT removes equal values, not duplicate business events. Two events with the same amount remain two events. Deduplication requires an event identity and a justified rule for recognizing repeated ingestion of the same event.
A LEFT JOIN can accidentally become an inner join in effect when a right-side condition is placed in WHERE. Consider customers LEFT JOIN jobs followed by WHERE jobs.status = 'completed'. Customers without matching jobs have NULL status, so the predicate is UNKNOWN and those rows are removed. If the intended question is all customers with their completed jobs where available, put the status restriction in the ON clause or prefilter the right relation. If the intended question is only customers who have completed jobs, the WHERE behavior may be appropriate. Placement follows meaning.
To ask whether a relationship exists without multiplying rows, EXISTS is often clear. Finding customers who have at least one open job does not require returning one customer row for every open job and then using DISTINCT to hide duplicates. A correlated EXISTS expresses the existence test directly. To find customers with no jobs, NOT EXISTS avoids the NULL trap that can arise from NOT IN when its subquery contains NULL. Choose the construct whose semantics match the question, and test unmatched and missing-value cases.
Join keys must carry the correct scope. An invoice number unique only within a company cannot safely join across companies by invoice number alone. Use the company identifier with it, or a globally unique internal key. A many-to-many bridge table introduces intentional repetition; reports must decide whether measures are allocated, counted once, or attached to each relationship. The fact that a join returns rows is weak evidence of business correctness. Check key uniqueness, unmatched counts, and reconciliation totals.
Progressive practice
- Foundation: write the four joined combinations for job 101 and reproduce the inflated totals.
- Application: explain why preaggregating both child tables to job_id repairs this fixture.
- Transfer: show why SUM(DISTINCT amount) fails for job 103's two equal-priced lines.
- Critique: move a completed-status filter between ON and WHERE in a left join and explain which customers disappear.
Worked reasoning for the practice
Each of two lines matches each of two payments, creating four combinations. Preaggregation reduces both child relations to one row per job, so the final join cannot repeat a job amount because of the other child collection. Job 103's two $200 lines are distinct line_id events, so their correct total is $400 even though amounts are equal. A WHERE test on the right-side status removes unmatched customers. An ON test retains them with NULL right-side fields. Check expected row counts and known totals before deciding which result is appropriate.
Subject-matched external readings
- SQLite — SELECT — Selection, grouping, joins, NULL-containing result populations, and aggregate-query behavior.
Unit 5 · Transactions and controls
Original Academy expansion: transactions, concurrency and auditability
A transaction groups operations that must succeed or fail together. Atomicity means the transaction's committed effects are all-or-nothing according to the database's guarantees. Consistency concerns preserving declared rules and application invariants. Isolation concerns what concurrent work can observe or interfere with. Durability concerns persistence after commit within the system's documented guarantees. These properties do not remove the need to design correct business operations. A transaction can atomically commit the wrong amount.
Suppose a payment event must be recorded and its allocation created. If the event is saved but the allocation fails, reporting may show unallocated cash. If an application subtracts inventory and then fails to create the shipment, stock can disappear from the system. Put the related operations in a transaction and make error handling explicit. In SQLite, BEGIN, COMMIT, and ROLLBACK manage an explicit transaction; savepoints support nested units of work. A BEGIN transaction is not itself a general nested-transaction mechanism.
Worked investigation: fail between two steps
The lab uses a simpler control table, control_totals, to demonstrate atomicity independently of the sales schema. Begin with two entries, reserve = 100 and available = 100. A fictional transfer of 30 subtracts 30 from available and adds 30 to reserve. The invariant is that their sum stays 200. First begin a transaction, subtract 30, and deliberately raise an application exception before the addition. Roll back. Both entries remain 100. Next perform both updates and commit; available becomes 70 and reserve 130. Verify the invariant after both the failure and success paths.
This does not prove that a transaction prevents every concurrency anomaly. A read-modify-write sequence can use stale information unless its isolation and locking behavior are appropriate. SQLite permits multiple readers but one writer at a time. Applications must handle lock contention and failures rather than treating every retry as harmless. Different engines and isolation levels provide different visibility and conflict rules. A migration plan must revisit these assumptions.
An idempotency key identifies one intended operation across retries. If a payment request times out after the server commits, blindly retrying can record the payment twice. A unique external event identifier lets the system distinguish a retry from a new payment. The rule must be enforced in the trusted data layer. A button being disabled in one browser is not a durable duplicate-prevention mechanism. The key also needs scope: different payment providers might use the same local event string.
Audit history should preserve who did what, when, under which identifier, and why, with suitable access controls. Updating a balance directly can hide the sequence of underlying events. Event records and reconciliations often make the process more inspectable. Do not promise that an ordinary audit table is tamper-proof merely because it is named audit. Its writers, retention, and protection determine its evidentiary value.
Backups and transaction control solve different problems. A transaction protects the integrity of one logical operation under its guarantees. A backup supports recovery from broader loss or corruption. A backup that has never been restored is an untested recovery assumption. Define recovery objectives and test a restoration in an isolated environment. Similarly, parameterized queries protect the boundary between data and SQL syntax; they do not automatically enforce authorization to the requested customer's records. Integrity, security, and recoverability are related but distinct.
Progressive practice
- Foundation: state the invariant for the two-entry transfer and verify both outcomes above.
- Application: explain why a payment retry after a timeout can create a duplicate without a stable idempotency identifier.
- Transfer: a database update succeeds but sending a confirmation email fails. Explain why rolling back a later transaction cannot unsend an email and describe the need for a reliable delivery workflow.
- Critique: an application concatenates a customer-supplied account string into SQL. Explain the separate roles of parameterization and authorization.
Worked reasoning for the practice
The sum remains 200 after a rollback and after the committed transfer. A timeout describes what the caller observed, not whether the server committed. A stable unique operation identifier supports recognizing the same request on retry. External messages are not normally part of the database's atomic transaction; a durable pending-message record and a retryable delivery process can coordinate them while accounting for possible duplicate delivery. Parameterization keeps supplied values from becoming executable SQL syntax. Authorization verifies whether the caller may act on that account. Both are needed.
Subject-matched external readings
Unit 6 · Business queries and validation
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.
Subject-matched external readings
- SQLite — SELECT — Selection, grouping, joins, NULL-containing result populations, and aggregate-query behavior.
- SQLite — Transactions — Transaction boundaries and engine-specific concurrency behavior.
Open runnable laboratories and source code