The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← Data Management and SQL for Business

Unit 4

Joins and duplicate counting

Learning objectives

  • Explain joins and duplicate counting in your own words.
  • Apply the principle to the worked business case.
  • Evaluate the answer and identify an assumption that could change it.

Joins and duplicate counting

A join combines matching records according to a stated condition. One-to-many relationships can multiply rows and inflate sums. Aggregate at the correct grain before joining or use distinct entities only when that matches the question.

Worked example

Joining one $1,000 invoice to two payment rows produces two invoice appearances. Summing invoice amount then reports $2,000 incorrectly.

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 joins and duplicate counting 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 is the core error? 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.

Advanced investigation: Many-to-many joins, temporal cohorts and a reconciled result

A join is a multiplication of matching row combinations. If an order has two payment rows and three refund rows, joining both raw child tables to that order produces six combinations. Summing payment amounts repeats each payment three times; summing refunds repeats each refund twice. DISTINCT on the numeric amount is not a repair because equal-value legitimate events can be different records. Aggregate each child to the intended parent grain before combining them.

Time changes the metric as well as the join. Orders created during January, payments received during January and refunds issued during January are different eligible event sets. A January order can receive a February payment; a January payment can concern a December order. Define whether the report is a cash-period event measure, an order-cohort collection measure or an as-of receivable. None should be casually labeled revenue without the relevant recognition rules.

Use half-open time intervals such as event_time ≥ start and event_time < next_start. They avoid having to guess the final fractional second of a month. Store an explicit time basis and account for the relevant business timezone before assigning periods. The fictional date-only fixture has no timezone conversion problem; a production timestamp system does. A clean SQL predicate does not resolve an ambiguous business definition.

Null and zero need deliberate treatment. A missing child aggregate after a left join may reasonably become zero when it means no recorded events. An unknown amount or an unclassified event should not automatically become zero. COUNT(*) after an outer join can count a placeholder row, whereas counting a nonnull child key counts matched events. Reconcile totals and row counts against independently understood source events, including orders with no payments and equal-value distinct payments.

A report is an executable claim with a lineage. Preserve the query, parameters, source snapshot and metric contract. Test a small hand-reconciled fixture before running a large dataset. If a business total changes, distinguish a query correction, changed data, a revised eligibility rule and actual performance; they imply different explanations.

Worked investigation

A fictional order has two distinct payments of 5,000 cents each: one on January 31 and one on February 1. It has refunds of 1,000 and 2,000 cents, both in February. A raw payment-refund join has four rows and yields 20,000 payment cents minus 6,000 refund cents = 14,000, which is wrong. Aggregate separately: 10,000−3,000 = 7,000 lifetime net collections. January cash-period net is 5,000; February is 5,000−3,000 = 2,000. The January order cohort may include all 7,000 only if its as-of horizon includes those February events. SUM(DISTINCT payment_amount) would incorrectly reduce the two real equal payments to 5,000.

Independent transfer

Add an unrelated order created in December with a 4,000-cent payment on January 15. Calculate January cash-period net and explain whether the January-created-order cohort changes. State the correct grain for combining event aggregates.

Transfer reasoning

January cash-period net becomes 9,000 cents. The January-created-order cohort does not gain the December order merely because its payment occurred in January. Aggregate payment and refund events separately at the order grain for cohort reporting, or aggregate the signed event stream at the period grain for cash-period reporting. Keep the time and eligibility contract explicit.

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

  1. Foundation: write the four joined combinations for job 101 and reproduce the inflated totals.
  2. Application: explain why preaggregating both child tables to job_id repairs this fixture.
  3. Transfer: show why SUM(DISTINCT amount) fails for job 103's two equal-priced lines.
  4. 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.

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.

Open the runnable laboratory

Complete current conceptual preparation

Join at a declared grain and choose a storage model for its workload

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. Preserve the existing job 101 case: billed 250,paid 100,open 150 become false 500,200,300 after a two-line/two-payment raw join. 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.

```sql WITH line_totals AS ( SELECT order_id,SUM(amount_cents) billed FROM order_lines GROUP BY order_id ), paid_totals AS ( SELECT order_id,SUM(amount_cents) paid FROM payments WHERE status='settled' GROUP BY order_id ) SELECT o.order_id,COALESCE(l.billed,0) billed, COALESCE(p.paid,0) paid, COALESCE(l.billed,0)-COALESCE(p.paid,0) open FROM orders o LEFT JOIN line_totals l ON l.order_id=o.order_id LEFT JOIN paid_totals p ON p.order_id=o.order_id ORDER BY o.order_id; ```

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.

Relationships change across time and organizational scope

Joining invoice_no alone is unsafe when it is unique only within company. Match the complete key(company_id,invoice_no), or an equivalent globally unique internal identifier. Joining current territory to historical orders answers current-attribution, not order-date-attribution. The preserved temporal case gives North 100/South 500 under half-open historical intervals and exposes double total 1200 under overlaps. An ordinary primary key on interval start cannot enforce nonoverlap. Check cardinality per event, not just the final total; a valid-looking 600 can still be assigned to the wrong territory.

Relational storage is one representation, not a universal physical layout

The earlier course assigned nonrelational concepts externally. Those concepts belong on site too. A hierarchical model arranges records in a parent-child tree. It naturally represents a catalog with nested parts when a child has one structural parent, but shared children need references or duplication. Older network models allow records to participate through multiple links; navigating pointer paths differs from declaring a relational result. Neither label establishes current suitability or speed. Ask what relationships must be traversed, changed atomically and audited.

A non-first-normal-form or nested representation permits collection-valued attributes, such as an order containing an array of lines. A document database commonly stores self-contained structured documents, often with nested objects and arrays. An order document can preserve the exact issued line-price snapshot, but embedding a mutable customer contact in a thousand orders creates a propagation policy: should old documents retain the issuance contact or follow the current contact? That is a semantic choice, not automatically a defect or advantage. Schema flexibility does not remove a schema; it moves part of its validation into conventions and application controls.

An object database persists objects, identity and relationships directly, sometimes supporting inheritance and methods under its model. Object-relational extensions add richer types and collections to relational systems. Object persistence avoids rebuilding an object graph manually, but does not establish that a serialized object remains compatible with future code or has correct transaction boundaries. Distinguish identity from equality: two equal-address objects may represent different entities; one enduring entity may change attributes. Mapping a relational system to application objects through an ORM also does not eliminate joins, fan-out, transactions or query-cost inspection.

XML represents ordered trees with elements, attributes and potentially mixed content. A document-oriented XML store may query tree paths and preserve document structure. Relational storage can also retain XML or JSON values with engine-specific operators. If a legal or historical document's order and markup are meaningful, flattening every element into an unordered relation can lose context unless the mapping preserves it. Conversely, storing all operational events as opaque documents can make cross-document constraints and reconciled reporting harder. Choose by the facts and operations, not by whether a format looks modern.

NoSQL families and distributed guarantees

A key-value store maps a key to a value and suits direct retrieval when the application knows the key; secondary search and multi-key constraints depend on its features. A document store indexes fields inside documents and supports nested business aggregates. A wide-column family model organizes flexible rows/column groups for defined access patterns; it is different from analytical columnar physical storage, which groups values by column for scans and compression. A graph model treats vertices and edges as first-class structures, useful for path and relationship queries. A fraud-network question can fit a graph while the authoritative payment ledger remains relational.

Replication copies data across nodes for availability or read scale; partitioning divides data across nodes. Neither automatically ensures a single up-to-date global result. Strong consistency and eventual convergence are different contracts. During a network partition, a distributed design may restrict availability to preserve particular consistency guarantees or accept operations whose conflicts need later resolution. The familiar CAP discussion concerns specific consistency and availability definitions under partitions, not an all-purpose instruction to choose any two desirable properties. Inspect the actual product, transaction scope, read/write settings, failure behavior and reconciliation policy.

Cloud-managed storage changes who operates infrastructure, not who owns the data definition or access policy. A managed database, object store, warehouse and serverless query service offer different execution and transaction models. Storage cost, requests, scans, egress, backups and monitoring all affect total cost. Encryption, identity, region, retention and recovery settings need explicit responsibility assignments. Moving to a service does not make a broken event identifier unique or prove a recovery copy is restorable.

Worked choice: one order in three representations

Represent order Q with line IDs L 1=1000 and L 2=2000, payment IDs P 1=P 2=P 3=500, and a customer reference. In normalized tables, query separate child aggregates. In a document, sum distinct keyed line entries and payment entries within the document; reject duplicate event IDs under its update contract. In a key-value cache, store a derived summary(billed 3000,paid 1500) with source version and expiration/rebuild policy. The cache is not a new authoritative payment history. If P 4=500 arrives, correct paid 2000/open 1000 and invalidate or update every affected representation under a declared consistency strategy.

For a cache lagging one update, the displayed paid 1500/open 1500 may be internally consistent with an older version while stale for current operations. Label the version/cutoff; do not merge the new payment count with the old amount and call it one state. If the business requires current credit-limit enforcement, a stale analytical cache is the wrong authority. A system can intentionally use multiple storage models, provided lineage, authority and failure recovery are clear.

Optional progressive practice

Guided model: reconstruct the multiplication

Two lines and three payments produce six joined pairs. Billed 9000 and paid 3000 are inflated; independent aggregates give 3000 and 1500. Changed fact: order R has one line and one payment. Its raw join is not inflated, so dividing every order's totals by a common factor corrupts R. Correct grain rather than a guessed multiplier.

Independent model: historical document or current master

An issued order document retains the agreed line prices and issuance contact; a current customer record supplies today's contact. Both can coexist with explicit meaning. Changed fact: the report promises the address known at issuance but joins only today's master. Add a preserved snapshot/history relationship and test it; changing from relational to document storage alone does not recover lost history.

Transfer model: cache authority

After P 4=500, the authoritative paid amount is 2000 and open 1000. An old cache still shows 1500 and 1500. Mark it stale and rebuild/update under the declared contract; do not use it to authorize another payment or credit decision that needs current state. Changed fact: it is an intentionally frozen prior-day dashboard. Its old value can be valid for that snapshot if clearly labeled and fully consistent with the preserved prior-day inputs.

Unit rubric: 20 points

Four points each for exact join/grain repair; scoped and temporal keys; comparison of relational/nested/object/XML/NoSQL representations; consistency/cloud/cache responsibilities; and changed-fact model selection. Complete model gives Q 3000/1500/1500, preserves equal-valued payment identities and explains document snapshots versus current masters without promising universal database superiority.

Optional source summary: OpenStax nonrelational systems was read for the range of hierarchical, nested, object, XML and nonrelational representations. The on-site explanations and Q-order comparison are original. SQLite SELECT was read for the stated relational join/filtering semantics; its dialect is distinguished from distributed product guarantees.

Developed study chapters

Original explanation, worked analysis and progressive optional practice.

Apply the idea

Joining one $1,000 invoice to two payment rows produces two invoice appearances. Summing invoice amount then reports $2,000 incorrectly.

What is the core error? Explain your reasoning, then identify one changed fact that could alter the conclusion.

Advanced worked record — a separate fictional scenario: A fictional order has two distinct payments of 5,000 cents each: one on January 31 and one on February 1. It has refunds of 1,000 and 2,000 cents, both in February. A raw payment-refund join has four rows and yields 20,000 payment cents minus 6,000 refund cents = 14,000, which is wrong. Aggregate separately: 10,000−3,000 = 7,000 lifetime net collections. January cash-period net is 5,000; February is 5,000−3,000 = 2,000. The January order cohort may include all 7,000 only if its as-of horizon includes those February events. SUM(DISTINCT payment_amount) would incorrectly reduce the two real equal payments to 5,000.

Independent transfer: Add an unrelated order created in December with a 4,000-cent payment on January 15. Calculate January cash-period net and explain whether the January-created-order cohort changes. State the correct grain for combining event aggregates.

Expanded transfer investigation: Why does SUM(DISTINCT line_amount) fail for two legitimate $200 lines?

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

Summing a repeated invoice after a one-to-many join. Row multiplication changes the grain of the result. 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.

Advanced transfer reasoning: January cash-period net becomes 9,000 cents. The January-created-order cohort does not gain the December order merely because its payment occurred in January. Aggregate payment and refund events separately at the order grain for cohort reporting, or aggregate the signed event stream at the period grain for cash-period reporting. Keep the time and eligibility contract explicit.

Expanded transfer reasoning: Equal amount is not duplicate event identity.

Progressive practice reasoning: 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.

Check understanding

Job 101 has lines $100 and $150 and payments $60 and $40. What does a direct join of both child tables produce?

  1. $500 in summed lines and $200 in summed payments
    Feedback

    Correct. Two lines times two payments produce four combinations and repeat each amount.

  2. $250 in summed lines and $100 in summed payments by default
    Feedback

    Incorrect. Those are correct base totals, but this direct join does not preserve them.

  3. One row per job because all foreign keys are valid
    Feedback

    Incorrect. Foreign keys do not collapse one-to-many combinations.

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.

My learning →