The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← Data Management and SQL for Business

Unit 3

Filtering and aggregation

Learning objectives

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

Filtering and aggregation

SELECT chooses expressions, WHERE filters rows, and GROUP BY creates groups for aggregates. HAVING filters aggregated groups. Be explicit about dates and missing values; SQL's NULL does not behave like an ordinary known value.

Worked example

SUM(amount) by customer answers a different question from selecting individual invoice amounts.

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 filtering and aggregation 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

Which clause groups invoice totals by customer? 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.

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

  1. Foundation: explain why COUNT(*) and COUNT(completion_date) may differ.
  2. Application: calculate the fixture's average payment-event amount and average paid amount per job.
  3. Transfer: specify how to include customers without jobs in a receipt report while distinguishing no events from unknown data.
  4. 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.

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

Extended text lesson

Continue with Keep the window, the row and the reporting period distinct for the full worked case, source readings and optional progressive practice.

Complete current conceptual preparation

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.

```sql 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.

```sql 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.

Apply the idea

SUM(amount) by customer answers a different question from selecting individual invoice amounts.

Which clause groups invoice totals by customer? Explain your reasoning, then identify one changed fact that could alter the conclusion.

Expanded transfer investigation: Four payments total $390 across three jobs. Which average is $130?

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

GROUP BY customer_id. Grouping defines the level at which an aggregate is calculated. 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.

Expanded transfer reasoning: Aggregate payments to the job grain, then average the three job totals.

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

Check understanding

Why can COUNT(*) exceed COUNT(completion_date)?

  1. COUNT(completion_date) counts distinct dates only
    Feedback

    Incorrect. DISTINCT would need to be requested separately.

  2. COUNT(completion_date) excludes NULL values
    Feedback

    Correct. The expression count omits NULLs while the row count includes the rows.

  3. COUNT(*) always excludes unfinished jobs
    Feedback

    Incorrect. A status filter must be stated; COUNT(*) alone does not apply one.

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 →