Lawfare Academy ยท Complete Data Management and SQL edition 6
Construct, explain and test a SQL result
Relational operations and SQL's practical differences
Selection chooses eligible rows, projection chooses attributes, a join matches relations, and grouping changes the result grain. SQL often retains duplicate result rows, so SELECT DISTINCT is a separate operation. UNION combines result sets and removes duplicate rows; UNION ALL preserves all rows. Neither knows which repeated-looking records are distinct business events. Use event identities and a declared duplicate policy. INTERSECT and EXCEPT can test set membership, but set equality alone cannot establish duplicate multiplicities.
A useful logical SELECT order is FROM/joins, WHERE, GROUP BY, HAVING, result expressions, DISTINCT and ORDER BY. Windows operate on the rows remaining after the relevant grouping/filtering stage. This is a semantic reasoning order; an optimizer can choose a different physical access plan while preserving results. A sorted input file does not guarantee query output order. Supply ORDER BY with a stable tie-breaker when reproducibility depends on sequence. LIMIT without a defined order is not a meaningful rule for choosing the highest-value records.
An original six-event ledger
Use events(id,account,day,status,amount_cents): E 1,A,2026-01-01,settled,1000; E 2,A,2026-01-31,settled,2000; E 3,A,2026-02-01,settled,500; E 4,B,2026-01-15,pending,3000; E 5,B,2026-01-20,settled,NULL; E 6,C,2026-01-21,settled,0. Each id is one actual synthetic event. NULL means amount unresolved, and 0 is a measured zero. The January settled population contains E 1,E 2,E 5,E 6, not the February receipt or the pending event. It has four events, three known amounts and a known subtotal 3000, while its complete amount remains unknown.
SELECT account,
COUNT(*) AS event_count,
COUNT(amount_cents) AS known_count,
SUM(CASE WHEN amount_cents IS NULL THEN 1 ELSE 0 END) AS unknown_count,
SUM(amount_cents) AS known_subtotal
FROM events
WHERE day >= '2026-01-01' AND day < '2026-02-01'
AND status = 'settled'
GROUP BY account
ORDER BY account;The rows are A:(2,2,0,3000), B:(1,0,1,NULL), C:(1,1,0,0). B is incomplete; C has a known zero. Replacing both with the same display zero would conceal their difference. The mean known settled January event amount is 1000 from(1000,2000,0), not 750 obtained by treating the unknown fourth event as zero. The mean over just A's two known events is 1500. Every denominator must identify its population.
WHERE filters events before groups form. Adding HAVING COUNT(*)>=2 keeps only A. Adding WHERE amount_cents>0 instead excludes the known-zero C and unknown B before grouping, changing the target rather than just its presentation. CASE can classify rows or implement conditional aggregates; make unmatched cases explicit. A CASE expression that returns NULL can intentionally leave an observation out of SUM/AVG, but cannot establish that the excluded population is irrelevant.
NULL and predicates require three-valued reasoning
For a missing amount, amount_cents=0 and amount_cents<>0 are both UNKNOWN, so WHERE keeps neither. IS NULL detects missingness. NOT(UNKNOWN) remains UNKNOWN. TRUE OR UNKNOWN is TRUE, while FALSE OR UNKNOWN is UNKNOWN. Parentheses clarify combinations of AND and OR; do not let precedence choose eligibility by accident. A customer with a NULL identifier and a customer numbered 0 are different states.
For an exclusion subquery containing a key and NULL, NOT IN may return no otherwise unlisted rows because absence cannot be established under its truth conditions. Correlated NOT EXISTS asks whether an equal qualifying row exists and can express the intended anti-join. The preserved four-customer case gives complete counterexamples. If NULL means the exclusion file is untrusted rather than merely an absent key, stop or flag the report under that policy; changing syntax alone does not resolve input reliability.
Subqueries, CTEs and membership
A scalar subquery should return the single quantity the query expects; more than one candidate row may behave differently by engine, so enforce cardinality rather than relying on a permissive choice. A correlated subquery refers to the outer row, such as EXISTS a settled event for that account. EXISTS tests membership without multiplying account rows by matching events. A common table expression names a relation for clarity; it is not inherently a cached temporary table or a correctness guarantee. State its grain and verify it.
To report accounts with at least 3000 known settled January cents, aggregate the explicit eligible events in a CTE and join or filter the one-row-per-account result. To report every account, begin from the complete account relation and LEFT JOIN the aggregate. Distinguish no matching event from a matching event with unknown amount by retaining counts. If business eligibility requires complete measures, impose unknown_count=0 explicitly; a known subtotal above a threshold is not necessarily the same rule as a complete balance above it.
Window calculations preserve rows
For A's complete history, ordering by(day,id) with ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW gives running totals 1000,3000,3500. A January-only window ends 3000; a February display of the lifetime window should show 3500. Filter the display after computing the required history, not before. The original representative ledger additionally demonstrates same-date peers and default frame behavior. A deterministic identifier can resolve tied rows while still differing from effective business order; define which order the metric needs.
WITH history AS (
SELECT id,account,day,amount_cents,
SUM(amount_cents) OVER (
PARTITION BY account ORDER BY day,id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_known
FROM events WHERE status='settled'
)
SELECT * FROM history
WHERE account='A' AND day >= '2026-02-01'
ORDER BY day,id;This returns E 3 with running_known 3500. A window that ignores NULL amounts still computes only a known subtotal when history is incomplete. Carry unknown-history counts for a trustworthy full balance. ROW_NUMBER assigns a sequence; RANK allows gaps after ties; DENSE_RANK does not. To choose the latest event per account, order by an appropriate timestamp and a unique tie-breaker, then filter row_number=1 in an outer query. It does not authorize discarding earlier events from storage.
Optional progressive practice
Guided model: a known zero and an unknown amount
January settled events are E 1,E 2,E 5,E 6, count 4. Known count 3, unknown count 1, known subtotal 3000. B has no known sum while C has known zero. Changed fact: E 5 is verified as 400 cents. The subtotal becomes 3400, known count 4 and unknown count 0; the full mean is 850. Preserve evidence for the correction rather than treating 400 as originally known.
Independent model: group eligibility
HAVING COUNT(*)>=2 after the stated settled January WHERE retains A only. If the question instead includes pending events, B has two January events but one unresolved amount. Changed fact: the manager asks for every account, including no events. Start from the account register and left join the aggregate. An event-only query cannot invent absent account rows.
Transfer model: a February screen
Compute A's settled history first to obtain 1000,3000,3500, then display February E 3 with 3500. Changed fact: the measure is February-only receipts. Filtering before aggregation is then correct and gives 500. Both numbers can be correct; the dashboard must name which contract it implements.
Unit rubric: 20 points
Four points each for population/logical operations; executable filtering/grouping and NULL reasoning; correct event-versus-account denominators; CTE/window ordering and display boundaries; and changed-fact validation. Complete model gives A 3000,Bincomplete,C 0 for January, correctly distinguishes the pending and February records, and explains both 3500 lifetime and 500 period-only February figures. No practice query is directed at production or learner records.
Optional source summary: SQLite SELECT was read for row filtering, grouping, duplicate handling and compound results. Its specified behavior supports the dialect examples; the six-event ledger, calculations and complete models are original.