Knowledge Institute · 8–10 minutes with practice

Stop a join from doubling the amount owed

Declare what a row represents before connecting invoices, customers and payments.

Business Practice Quick Courses

Learning objectives

Learn

An invoice table might have one row per invoice, while a payments table has one row per payment. Both can be correct. A detail join matches a single invoice to every payment against it. That is useful for showing the individual transactions, but it changes the meaning of each result row. An amount that appeared once can now appear several times. Before adding numbers, decide what must appear once.

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.

Derive fan-out instead of treating it as a mysterious SQL defect

An inner join returns every matching pair. If one parent has m eligible lines and n eligible payments, their independent child joins can produce m*n combinations. Each line amount appears n times, each payment amount m times. Keys and foreign keys may all be valid while the sums are wrong. The repair is not to divide by two, because different parents have different multiplicities. Aggregate each fact to the agreed parent grain before combining it.

For a new independent fixture, order Q has two line records worth 1000 and 2000 cents, three distinct payments of 500 each, and no refund. The raw line-payment join has six rows. Billed sum 9000 repeats each line three times, while paid sum 3000 repeats each payment twice. Correct billed 3000,paid 1500,open 1500 come from separate aggregates. SUM(DISTINCT payment amount) would instead return 500, deleting two legitimate equal payments. Event identity, not value equality, defines whether an event is repeated.

The zero-fill convention assumes an absent child aggregate means no recorded events in a complete feed. It does not turn an unknown amount into zero. Keep original population and missingness checks. A customer-status predicate in WHERE after an outer join can remove unmatched accounts; put the eligibility predicate in ON or prefilter the child when the intended target retains every parent. To ask only whether a tag exists, use EXISTS rather than joining every tag and multiplying an order's money. For a tag-level report, intentional repetition requires a declared allocation/counting policy.

Apply

Invoice A is $1,000 with payments of $300 and $400. Invoice B is $500 with no payment. A left join that preserves both invoices yields two rows for A and one for B. Summing the invoice amount in those rows would give $2,500 instead of the true $1,500. Aggregate payments to one row per invoice first, then join. A has $700 paid and $300 open. B has no matched payment, so under the stated rule it has $0 paid and $500 open. Confirm the total outstanding is $800, agreeing with $1,500 minus $700.

Check source constraints too. A stable unique invoice identifier gives payments a precise reference. If an unmatched payment exists, report or resolve it under an explicit policy rather than making it vanish in a join.

Optional check

If invoice A has three payments instead of two, how many rows does a simple invoice-to-payment detail join normally return for A?

Show the explained answer

Three matching rows. That is correct for per-payment detail. For invoice totals, group back to the invoice level or pre-aggregate payments and verify the total against the source.

Sources and further reading

Continue in Lawfare Academy

Full course · Data Management and SQL for Business