Lawfare Academy ยท Complete Data Management and SQL edition 6

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.

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.