Relational Data & SQL — Applied edition — full text

8 original lessons · 44 planned hours · unpiloted applied edition · self-paced

Course details & full text

Eight connected applied SQL units with original teaching, local practice, explained keys and a reproducible project; the full planned 108h semester remains unfinished. Classroom/audio covers core teaching; complete keys and model outputs are separate references.

The actual Business profile requires: • spreadsheet-foundations.O1–O3: inspectable tidy workbooks, references/lookups/aggregation/validation with control totals, and stress-tested scenario models with an audit log. • data-ethics-stewardship.O1–O2: purpose/necessity/identifiability reasoning and task-based access, retention, provenance and sharing controls. • introductory-statistics.O1: population/sample/unit/variables/missingness definitions and accurate descriptive comparisons. Those expanded programme competencies are not automatically established by completing shorter existing introductory lessons. Keep evidence or use the diagnostic below; no prerequisite course is reauthored here. Python is a local runner implementation, not a learner prerequisite or duplicate Python course. Statistical reasoning is applied, not retaught as a replacement course. Fee cents are units/control data, not a competing accounting unit.

This is the eight-unit applied self-study edition of Relational Data & SQL. Its 44-hour workload is an unpiloted estimate including reading, practice, project, review, revision and later-day transfer. Unit 5 is counted once. The retained 12-week/108-hour intermediate semester remains unfinished. Independent assistant content/technical checks do not replace human subject review, learner piloting or independent assessment; those remain pending. Self-review and saved review marks are not grades, credentials or evidence of independently demonstrated competence. SQL is not executed in the browser. Use the linked local setup or label execution pending. Classroom/audio delivery: original core explanations, worked examples and practice prompts are included. Complete explained answer keys, saved model queries and frozen result tables are reference-only in this classroom/audio projection, not automatically recited. They remain complete in the lesson player answer disclosures, complete course text and labelled solutions/resources. For this course, Whole lesson audio means this classroom sequence, including worked examples; it is not narration of the complete reference library.

  • U1: frame a question and small relational model at explicit grain/keys.
  • U2: select/filter/order/calculate with tested boundaries and units.
  • U3: investigate missing, duplicate, invalid and unmatched records responsibly.
  • U4: aggregate and reconcile with correct denominators and empty behavior.
  • U5: preserve entity populations across joins and demonstrate counterexamples.
  • U6: compose CASE/subquery/CTE analyses with inspectable stage contracts.
  • U7: communicate measures, logical bounds and limitations without causal overclaim.
  • U8: deliver a reproducible local project with controls and changed-data evidence.
Practice files & complete project

Download once; all fixtures are fictional. Keep your first attempt before reading the model. No upload is used.

LESSON 1 OF 8 · PLANNED 300 MINUTES

Unit 1 — Ask a question a table can answer

STEP 1 OF 6

Your objective

define the grain, population and keys of a small relational analysis; justify a two-table model without repeating session facts.

STEP 2 OF 6

The idea

Unit 1 — Ask a question a table can answer

Outcome U1: define the grain, population and keys of a small relational analysis; justify a two-table model without repeating session facts. Preparation: basic table reading, source totals and the retained prerequisite screen in COURSE.md. Suggested work: about five hours including practice and revision; unpiloted, not a minimum attendance requirement.

1. A decision is not yet a database question

A fictional neighbourhood workshop coordinator asks, “Are our workshops being used?” That could mean seats booked, seats attended, distinct people reached, or capacity filled. Each is a different question. SQL can calculate the wrong one perfectly.

For this course we ask two narrower questions: “How many booked seats are represented by these records?” and “What do the recorded attendance counts establish, given missing attendance?” The first population is the set of supplied booking records. The second needs an explicit missingness rule. We will not infer unique people, satisfaction, causes, or future demand. The data are invented for learning, not a report on a real organization.

A good question sentence names entity, time scope, measure, inclusion rule and intended use. Example: “For open sessions listed in the September synthetic fixture, compare booked seats with listed capacity to identify records worth checking before planning the next round.” This does not promise that a high booking ratio proves a session is popular or effective. It does tell us which records and denominator we need.

Write that sentence before SQL. If you cannot say whether a cancelled session belongs in a denominator, the obstacle is an unresolved definition, not missing syntax.

2. One row means one thing

The sessions table has one row per scheduled session. Session 101 is Repair at North on September 3, capacity 6, status open. The registrations table has one row per booking record, not one row per person or seat. Booking 1001 reserves two seats in session 101; booking 1002 reserves one. Therefore ten booking rows can represent fourteen booked seats.

A booking_ref is an invented booking contact reference. L01 occurs in more than one booking. It does not identify every person attending: a two-seat booking has only one reference. Even counting distinct references cannot establish unique people reached. A database column can be a perfectly good identifier for one purpose and inadequate for another.

The grain is the entity described by one row. A measure's grain matters too. capacity=6 belongs to session 101. seats=2 belongs to booking 1001. If the session row is repeated beside three bookings, the capacity does not become eighteen. You will investigate this failure directly in Unit 5.

Two-table grain and keys

Complete text alternative: a sessions row has primary key session_id; a registrations row has primary key reg_id and foreign key session_id. One session can have zero, one or many registrations. Each constrained registration refers to exactly one existing session. Capacity is stored once per session; booked and attended seat counts are stored once per registration. The arrow represents the relationship, not data movement.

3. Identity, candidate keys and repeated facts

A primary key is the chosen unique identifier for table rows. session_id and reg_id serve that role. A candidate key is any minimal set of fields guaranteed by the domain rules to identify a row uniquely. Looking unique in this tiny sample is not enough. Dates repeat in real schedules; two sessions may share a site, topic and date; names may change. The schema does not declare those combinations to be candidate keys.

A foreign key connects a child row's identifier to a parent key. registrations.session_id may repeat because several bookings can refer to one session. Repetition of a foreign key is not a duplicate-record error. Repetition of the same reg_id in a supposedly one-row-per-booking table is an identity conflict.

Imagine a flat sheet containing reg_id, session_id, topic, site, capacity, seats. If one session has three bookings, its topic, site and capacity appear three times. A correction to capacity could update only two rows, leaving incompatible versions of one fact. Moving session facts into sessions makes the intended dependency visible: session_id determines the session attributes. Booking facts remain in registrations, where reg_id determines them. This is a small normalization example, not a full treatment of functional dependencies or normal forms.

“Remove every repeated value” is not normalization. Two sessions can legitimately have capacity 4; two registrations can legitimately cost 600 cents. The aim is to store each fact at its proper entity grain, not to erase equal values.

4. Read the contract before loading

Open data/schema.sql. The teaching schema requires integer seat counts; seats must be positive; attendance may be unknown but, when recorded, is between zero and booked seats; fees cannot be negative. STRICT tables reject unsuitable types for these fields. PRAGMA foreign_keys=ON enables relationship enforcement on the connection. These rules catch some impossible records, not every false record. A made-up but internally valid attendance count could still pass.

starts_on is text in consistently padded YYYY-MM-DD form. That makes the supplied dates sortable as text. The schema does not validate every possible calendar date. A real intake would need an authoritative date-validation rule. booking_ref is required but not unique. The schema also does not impose cross-table capacity limits: a session could have more booked seats than capacity, which should trigger investigation rather than be assumed impossible.

The intake table is deliberately less constrained. It represents raw rows awaiting investigation. It is not silently added to the trusted registration population. Preserve raw evidence; do not “fix” it by inventing missing parents.

STEP 3 OF 6

Original explanation and worked demonstration

5. Trace a control before running anything

Read the ten base registration rows in DATA-DICTIONARY.md. Add seats: 2+1+1+2+2+1+2+1+1+1 = 14. Count rows: 10. Distinct booking references are 8, but they are not eight unique attendees. These are three different measures with different meanings.

Now run python3 run.py base --query u01_inventory. The result should have columns booking_rows, booking_refs, booked_seats and one row 10,8,14. Save the result, fixture name and runtime label. Execution checks that this SQL produced this result on this data. Your earlier arithmetic is a separate control; matching it is useful evidence, but it does not prove the question was suitable.

STEP 4 OF 6

Try it yourself

Practice and checkpoint

Complete G1 then I1 in WORKBOOK.md before opening the key. G1 uses the worked base fixture; I1 uses different October sessions. Draw the relationship or write its text equivalent. Explain which repetitions are expected and which need investigation. Checkpoint C1 asks you to reject the claim “ten registrations means ten people attended.”

Do not proceed merely because your row count matches. You should be able to explain why a session with no registrations still exists and why capacity cannot be summed across repeated booking rows. If those explanations are unclear, annotate the two tables by hand and retry the checkpoint. Your final project begins now: save a question-and-grain.md note with the question, population, table grains, keys and three claims the data cannot support.

Applied SQL workbook — attempt first, then inspect the key

Keep this workbook locally in text or on paper. A drawing may always be replaced by a structured text list. No login, upload, timed exam, external assessor or certificate is required or implied. For each task retain prediction → SQL/reasoning → observed result → discrepancy → correction. Paper tracing is valid reasoning evidence but is not executed SQL.

Use base for G tasks, independent for I tasks and changed only for delayed transfer. Model query names are provided as references, not commands to copy before attempting. Complete the linked Unit 5 workbook in its original package.

Unit 1: grain and keys

G1. Write a bounded question for the coordinator. Define one row in each trusted table, identify primary/foreign keys and state whether booking_ref is a key. Calculate base booking rows, distinct booking references and booked seats by hand; then write a query returning the three. Explain why none is necessarily unique people attended. Sketch the relationship and identify the dependency that allows capacity to be stored once.

I1. Without referring to the base numbers, calculate the same three controls for independent. A proposed flat export repeats session 203's capacity next to two bookings. Explain the update anomaly if only one copy changes. Name a plausible sample-unique field or combination that is not guaranteed to be a candidate key by this contract.

C1. Correct this sentence: “Ten rows means ten people attended, and three repeated session IDs are three duplicate sessions.” Your correction must define the entity being counted.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Open-response practice: keep your attempt, then compare the explained answer and rubric. There is no automatic grading or submission to a teacher; review marks are not grades.

STEP 5 OF 6

Worked answer & self-check

Explained key — compare after keeping your attempt

Explained key — Units 1–4

Attempt first. Equivalent SQL earns the same self-review result if its population, grain, missingness and output contract are correct. A memorized number without reasoning is incomplete. The model queries are in queries/; verified expected tables are in expected-results.json and expected-tables.md.

G1 / I1 / C1: identity before arithmetic

G1: sessions describe sessions; registrations describe bookings. Primary keys are session_id and reg_id. registrations.session_id is a many-to-one foreign key. booking_ref can repeat and represents a booking contact reference, not every participant. Base controls are 10 booking rows, 8 references, 14 seats (u01_inventory). None measures actual unique attendees. A question such as “What fraction of listed open-session capacity is booked?” is answerable; “How many different people benefited?” is not.

I1: independent has 5 bookings, 4 references, 7 seats. Session 203 has two bookings but one capacity fact (4). If a flat export changed one capacity to 5 and left the other at 4, it would contain conflicting statements about the same session. Store capacity at session grain; do not choose whichever duplicate supports your preferred result. starts_on happens to be unique here, but the contract permits multiple sessions on one day, so sample uniqueness is not proof of a candidate key.

C1: ten rows means ten booking records, not ten people or ten attendances. Repeated session IDs in bookings are expected foreign-key repetition; a repeated primary session key in sessions would violate the chosen identity constraint. A sound answer explains both repetitions rather than calling every repeated number a duplicate.

Self-review U1: complete requires the question/population, both grains, both primary keys, relationship, all three controls and the unsupported-reach caveat. Partial if arithmetic is right but entity meanings are unclear; not yet if you equate records with people or sum repeated capacity as new capacity.

Saved model queries and expected fixture tables — static reference, not execution

-- Original model query; attempt workbook task before reading.
SELECT COUNT(*) AS booking_rows,COUNT(DISTINCT booking_ref) AS booking_refs,
 SUM(seats) AS booked_seats FROM registrations;
sql-applied-course / base / u01_inventory — frozen expected output, not executed in this browser
booking_rowsbooking_refsbooked_seats
10814
sql-applied-course / independent / u01_inventory — frozen expected output, not executed in this browser
booking_rowsbooking_refsbooked_seats
547
sql-applied-course / changed / u01_inventory — frozen expected output, not executed in this browser
booking_rowsbooking_refsbooked_seats
334
sql-applied-course / empty / u01_inventory — frozen expected output, not executed in this browser
booking_rowsbooking_refsbooked_seats
00NULL

Compare your answer

  • Bounded question, both grains and keys, valid dependency explanation, controls and unsupported-reach caveat
  • Rows equated with people; repeated session facts treated as new entities
  • 3 — demonstrated in this attempt: correct result and defensible reasoning, with requested evidence and transfer test.
  • 2 — partly demonstrated: central method works but a definition, control, edge case or reproduction detail is missing; revise.
  • 1 — not yet demonstrated: an important grain, missingness, denominator or execution error remains, even if one answer happens to match.
  • 0 — no assessable evidence: task absent or only a copied answer with no reasoning/attempt trail.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • U1: frame a question and small relational model at explicit grain/keys.

Do not proceed merely because your row count matches. You should be able to explain why a session with no registrations still exists and why capacity cannot be summed across repeated booking rows. If those explanations are unclear, annotate the two tables by hand and retry the checkpoint. Your final project begins now: save a question-and-grain.md note with the question, population, table grains, keys and three claims the data cannot support.

Next lesson: Unit 2 — Select deliberately, filter precisely, sort completely →

LESSON 2 OF 8 · PLANNED 240 MINUTES

Unit 2 — Select deliberately, filter precisely, sort completely

STEP 1 OF 6

Your objective

write selection and calculation queries with explicit boundaries, useful column names and deterministic ordering.

STEP 2 OF 6

The idea

Unit 2 — Select deliberately, filter precisely, sort completely

Outcome U2: write selection and calculation queries with explicit boundaries, useful column names and deterministic ordering. Suggested work: four hours including tasks and corrections, unpiloted.

1. A result is a new table-shaped view

A SELECT does not move or edit source rows. It describes a result. Start with:

SELECT session_id,topic,site,starts_on,capacity
FROM sessions
WHERE status='open'
ORDER BY starts_on,session_id;

FROM identifies the source, WHERE keeps rows satisfying a condition, SELECT chooses output columns and expressions, and ORDER BY arranges the result. This is a helpful reasoning order, not a guarantee of the engine's physical execution plan. The semicolon ends the statement. SQL string values use single quotes; column names here do not require quotes.

In base, this query returns sessions 101,102,103,105,106. Session 104 is excluded because it is cancelled, not because its capacity happens to be zero. A zero capacity might have another explanation elsewhere. The condition should express the actual inclusion rule.

Prefer explicit columns to SELECT * in saved deliverables. A result with only needed fields is easier to inspect, and adding a new source column does not silently change your output contract. A column alias such as AS booked_seats makes an expression readable; it does not change the stored field.

2. Predict boundary rows

To inspect bookings reserving at least two seats:

SELECT reg_id,session_id,seats FROM registrations
WHERE seats>=2 ORDER BY seats DESC,reg_id;

The base IDs are 1001,1004,1005,1007. The operator >= includes exactly two. Replacing it with > would return none in this fixture. Boundary testing is often more informative than checking an obvious interior value.

Compound conditions need care. AND binds more tightly than OR. Write parentheses when the intended groups matter:

WHERE (site='North' OR site='South') AND status='open'

Without the parentheses, site='North' OR site='South' AND status='open' would allow a cancelled North session. The current base cancelled session is in South, so base alone may hide the error. Explain a hypothetical cancelled North row that would distinguish the two conditions. You need not add real data to test the reasoning.

3. Use a closed start and open end for a date window

For September 1 through September 10 inclusive in this date-only fixture:

WHERE starts_on>='2026-09-01' AND starts_on<'2026-09-11'

This returns 101,102,103. Session 104 starts exactly at the excluded end. The half-open form gives adjacent windows a clean boundary: the next window starts on the 11th. BETWEEN includes both ends; it is not wrong, but its inclusion rule must match the question.

These comparisons work because every supplied date is in the same zero-padded ISO-style format. Do not generalize text sorting to 9/3/26, mixed formats or time zones. Timestamps, local times and daylight-saving changes require an explicit design outside this bounded sequence. Our date fixture contains none of those complications.

4. A sort is incomplete if ties have no rule

SQL does not promise the order of rows without ORDER BY. Even with it, rows tied on every ordering expression may be returned in any order. ORDER BY seats DESC puts larger bookings first but leaves all two-seat bookings tied. Adding the unique reg_id creates a complete ordering. That matters for comparing result files and for selecting a reproducible first few rows.

A LIMIT 3 query without a full ordering is not “the top three” in a meaningful, repeatable sense. Choose whether tied measurements should all be included; that analytical decision is separate from making an arbitrary selection deterministic. In this course we sort every multirow model result by keys after the meaningful sort fields.

STEP 3 OF 6

Original explanation and worked demonstration

5. Numbers have storage units and display units

fee_cents is a nonnegative integer administrative booking fee amount in this synthetic case. It is not cash received, recognized revenue, tax or profit. The course uses it only to teach units, equal values and rounding.

For display:

SELECT reg_id,fee_cents,ROUND(fee_cents/100.0,2) AS fee_cad
FROM registrations ORDER BY fee_cents DESC,reg_id;

The .0 forces real-number division. In SQLite, integer division can truncate: 250/100 gives 2, while 250/100.0 gives 2.5. Rounding a displayed number does not format it as a currency string; JSON may show 6.0, not 6.00. That is a representation difference, not a changed amount.

Preserve the integer cents and aggregate them before converting for display. Binary floating-point cannot exactly represent many decimal fractions. These small fixtures use integer totals and rounded display rates; they do not implement a financial settlement system or a general decimal policy. Do not round every intermediate rate and then expect exact reconciliation.

STEP 4 OF 6

Try it yourself

Practice and checkpoint

Complete G2: predict the four large-booking IDs and the three date-window IDs, then run the model queries only after writing your own. Complete I2 on the independent fixture: show open sessions, two-seat bookings and fee amounts, sorted by fee descending and ID. Test an exactly two-seat row, a row outside the date window and two equal fees.

Checkpoint C2 requires a two-sentence explanation of why ORDER BY fee_cents DESC,reg_id is more reproducible than sorting by fee alone, and why integer division can lose cents. Save a selection.sql query and a short boundary-test note for your cumulative project. If a query produces zero rows, inspect the inclusion rule before assuming the database is broken.

Unit 2: selection and order

G2. Produce (a) open sessions with date, capacity and stable order; (b) bookings of at least two seats sorted by seats descending then ID; (c) sessions in September 1–10 inclusive using a half-open window; (d) booking fee cents and displayed CAD sorted descending by fee then ID. Predict IDs before execution. Explain >= versus > at two seats and 250/100 versus 250/100.0.

I2. On independent, show open sessions and all two-seat bookings. Display each fee in CAD. Supply a boundary test for the start/end of an October 2–9 inclusive window. Explain what changes if you omit the ID tie-breaker. Write a hypothetical cancelled North row that exposes an unparenthesized OR/AND filter error.

C2. In two sentences, explain deterministic order and integer truncation. Run SELECT 250/100 AS integer_result,250/100.0 AS real_result; from your own saved file if executing locally.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Open-response practice: keep your attempt, then compare the explained answer and rubric. There is no automatic grading or submission to a teacher; review marks are not grades.

STEP 5 OF 6

Worked answer & self-check

Explained key — compare after keeping your attempt

G2 / I2 / C2: boundary and order

G2: u02_open_sessions returns 101,102,103,105,106 in date/ID order. u02_large_bookings returns 1001,1004,1005,1007, all two-seat bookings. u02_date_window returns 101,102,103; the exclusive end is September 11. u02_fee_display sorts 1200-cent bookings 1001,1004,1005,1007, then 600-cent bookings 1002,1003,1008,1009,1010, then zero-fee 1006. CAD display values are 12,6,0 respectively. >=2 retains the boundary; >2 selects none. 250/100 is integer 2; 250/100.0 is real 2.5.

I2: open session IDs 201,202,203; two-seat bookings 2003,2004. Fee sort order is 2003,2004,2001,2002,2005, displaying 5,5,2.5,2.5,0 CAD. An October 2–9 inclusive window uses starts_on>='2026-10-02' AND starts_on<'2026-10-10': includes 201 at the start and 203 on the final included date, excludes 204 at the end boundary. The supplied September query intentionally returns no independent rows; change the dates in your own file rather than pretending the fixture changed.

An imagined North cancelled session exposes site='North' OR site='South' AND status='open': the North branch alone is true. Parenthesizing the site alternatives makes open status apply to both. Omitting reg_id after fee leaves equal-fee rows tied, so their relative order is unspecified.

C2: unique-key tie-breakers make repeated outputs comparable. Integer division can discard the fractional unit; force real division for a display amount, while preserving integer cents as the source/control unit.

Self-review U2: complete requires correct selected IDs, boundary logic, complete order and a units explanation. Partial if values match but equal-fee ties are unspecified; not yet if the date end or cents conversion changes the intended population/value.

Saved model queries and expected fixture tables — static reference, not execution

-- Original model query; attempt workbook task before reading.
SELECT session_id,starts_on FROM sessions
WHERE starts_on>='2026-09-01' AND starts_on<'2026-09-11'
ORDER BY starts_on,session_id;
sql-applied-course / base / u02_date_window — frozen expected output, not executed in this browser
session_idstarts_on
1012026-09-03
1022026-09-04
1032026-09-10
sql-applied-course / independent / u02_date_window — frozen expected output, not executed in this browser
session_idstarts_on
No rows returned.
sql-applied-course / changed / u02_date_window — frozen expected output, not executed in this browser
session_idstarts_on
No rows returned.
sql-applied-course / empty / u02_date_window — frozen expected output, not executed in this browser
session_idstarts_on
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT reg_id,fee_cents,ROUND(fee_cents/100.0,2) AS fee_cad
FROM registrations ORDER BY fee_cents DESC,reg_id;
sql-applied-course / base / u02_fee_display — frozen expected output, not executed in this browser
reg_idfee_centsfee_cad
1001120012
1004120012
1005120012
1007120012
10026006
10036006
10086006
10096006
10106006
100600
sql-applied-course / independent / u02_fee_display — frozen expected output, not executed in this browser
reg_idfee_centsfee_cad
20035005
20045005
20012502.5
20022502.5
200500
sql-applied-course / changed / u02_fee_display — frozen expected output, not executed in this browser
reg_idfee_centsfee_cad
30035005
30012502.5
30022502.5
sql-applied-course / empty / u02_fee_display — frozen expected output, not executed in this browser
reg_idfee_centsfee_cad
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT reg_id,session_id,seats FROM registrations
WHERE seats>=2 ORDER BY seats DESC,reg_id;
sql-applied-course / base / u02_large_bookings — frozen expected output, not executed in this browser
reg_idsession_idseats
10011012
10041022
10051022
10071032
sql-applied-course / independent / u02_large_bookings — frozen expected output, not executed in this browser
reg_idsession_idseats
20032022
20042032
sql-applied-course / changed / u02_large_bookings — frozen expected output, not executed in this browser
reg_idsession_idseats
30033022
sql-applied-course / empty / u02_large_bookings — frozen expected output, not executed in this browser
reg_idsession_idseats
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT session_id,topic,site,starts_on,capacity FROM sessions
WHERE status='open' ORDER BY starts_on,session_id;
sql-applied-course / base / u02_open_sessions — frozen expected output, not executed in this browser
session_idtopicsitestarts_oncapacity
101RepairNorth2026-09-036
102RepairSouth2026-09-044
103DesignNorth2026-09-105
105RepairNorth2026-09-174
106DesignSouth2026-09-183
sql-applied-course / independent / u02_open_sessions — frozen expected output, not executed in this browser
session_idtopicsitestarts_oncapacity
201DesignNorth2026-10-023
202RepairSouth2026-10-032
203RepairNorth2026-10-094
sql-applied-course / changed / u02_open_sessions — frozen expected output, not executed in this browser
session_idtopicsitestarts_oncapacity
301RepairNorth2026-11-014
302DesignSouth2026-11-022
303DesignNorth2026-11-033
sql-applied-course / empty / u02_open_sessions — frozen expected output, not executed in this browser
session_idtopicsitestarts_oncapacity
No rows returned.

Compare your answer

  • Correct inclusions at boundaries, unique tie-breaker, explicit columns and cents conversion
  • Wrong date/threshold boundary; unstable output; truncated money display
  • 3 — demonstrated in this attempt: correct result and defensible reasoning, with requested evidence and transfer test.
  • 2 — partly demonstrated: central method works but a definition, control, edge case or reproduction detail is missing; revise.
  • 1 — not yet demonstrated: an important grain, missingness, denominator or execution error remains, even if one answer happens to match.
  • 0 — no assessable evidence: task absent or only a copied answer with no reasoning/attempt trail.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • U2: select/filter/order/calculate with tested boundaries and units.

Checkpoint C2 requires a two-sentence explanation of why ORDER BY fee_cents DESC,reg_id is more reproducible than sorting by fee alone, and why integer division can lose cents. Save a selection.sql query and a short boundary-test note for your cumulative project. If a query produces zero rows, inspect the inclusion rule before assuming the database is broken.

Next lesson: Unit 3 — Unknown is not zero; suspicious is not disproved →

LESSON 3 OF 8 · PLANNED 300 MINUTES

Unit 3 — Unknown is not zero; suspicious is not disproved

STEP 1 OF 6

Your objective

distinguish missing, zero and invalid values; expose duplicate identities and raw-record problems without silently repairing the source.

STEP 2 OF 6

The idea

Unit 3 — Unknown is not zero; suspicious is not disproved

Outcome U3: distinguish missing, zero and invalid values; expose duplicate identities and raw-record problems without silently repairing the source. Suggested work: five hours, including a quality log and independent task; unpiloted.

1. Three states that should not collapse

Booking 1002 has attended=0: attendance was recorded and none of its booked seats attended. Booking 1003 has attended=NULL: no attendance value is supplied. Session 106 has no booking rows at all. These are not interchangeable observations.

NULL is a marker of absent information, not a special number or empty text. It can mean different things in different datasets. Our dictionary says only “attendance count not recorded in the supplied fixture.” Do not infer refusal, absence, deletion or late arrival.

A comparison with NULL generally produces unknown rather than true or false. A WHERE clause keeps true results; unknown results do not pass. Consequently WHERE attended=0 selects the two base zero-attendance bookings, but it does not select the missing ones. WHERE attended<>0 also excludes missing ones. Those two filters do not partition all ten rows.

Use IS NULL and IS NOT NULL:

SELECT reg_id,session_id,seats FROM registrations
WHERE attended IS NULL ORDER BY reg_id;

The base result is (1003,101,1) and (1007,103,2): two records representing three booked seats. WHERE attended=NULL does not answer this question. There is no ordinary value on the right to compare with.

2. Audit the denominator alongside the total

COUNT(*) counts result rows. COUNT(attended) counts non-NULL attendance values. On base they produce 10 and 8. SUM(attended) ignores NULL inputs and adds the eight recorded values to 8. That sum is a count of recorded attended seats, not necessarily the final attendance total.

The record coverage is 8/10 = 80%. But the seat coverage is 11/14 ≈ 78.57%, because missing bookings reserve three seats. Coverage depends on what is being counted. Do not use a record-coverage percentage as a seat-coverage denominator.

COALESCE(attended,0) replaces missing values in an expression with zero. It does not repair the evidence. It is appropriate only when zero is a justified presentation or modeling convention and the missingness remains visible. In Unit 7 we use zero for an additive lower-bound component while separately displaying unknown seats. We never claim that missing attendance was observed to be zero.

Missingness states

Complete text alternative: three separate boxes: “Recorded zero: booking 1002, one booked seat, attendance 0”; “Unknown: booking 1003, one booked seat, attendance NULL”; “No booking row: session 106, capacity 3.” The first is an observed count, the second lacks a count, the third has no entity in the child table. No arrow equates them.

3. A staging table is an evidence queue

The raw intake table contains six rows. Ingest IDs 1 and 2 both claim registration 9001 with identical attributes. Ingest 3 points to session 999, which is absent. Ingest 4 lacks a registration ID. Ingest 5 requests zero seats. Ingest 6 records attendance 2 for a one-seat booking. They are deliberately problematic learning records, not additions to the trusted counts.

A duplicate-identity query groups by the proposed identity:

SELECT reg_id,COUNT(*) AS intake_rows FROM intake
WHERE reg_id IS NOT NULL
GROUP BY reg_id HAVING COUNT(*)>1 ORDER BY reg_id;

You will learn GROUP BY systematically next unit; here read its purpose: put claims with the same nonmissing identity together, count them, then keep groups with more than one claim. The result is (9001,2). That does not tell you which source message is authoritative or whether a retransmission should be retained in an audit history.

Do not use SELECT DISTINCT fee_cents as a duplicate-record detector. Many legitimate bookings share a price. Conversely two conflicting rows can claim the same ID while differing in seats; exact-row DISTINCT would not resolve that conflict. An identity rule and provenance are needed.

The supplied u03_invalid_intake query flags missing IDs, missing seat counts and impossible seat/attendance counts. It returns ingest IDs 4,5,6. It does not find the orphan session or duplicate identities; those are separate checks. A green check means a particular rule passed, not that the entire table is correct.

STEP 3 OF 6

Original explanation and worked demonstration

4. Constraints are guardrails, not truth machines

The trusted registration schema rejects duplicate primary keys, missing parent sessions, nonpositive seats, attendance above seats and negative fees. The local tests execute each rejection in a fresh in-memory database. They also verify that missing attendance is permitted, because unknown is a valid state in this case.

SQLite can generate an INTEGER PRIMARY KEY when an insertion supplies NULL. That is not an authoritative correction of a missing source identity. The intake check must flag a missing reg_id before admission; our supplied trusted fixtures always state their IDs explicitly.

A foreign key checks the existence of an identifier, not the truth of the association. Booking 1001 could be mistakenly linked to existing session 102 and still satisfy the relationship constraint. Similarly, a believable but wrong attendance count can pass a numeric check. Validation combines structural rules, source comparison and domain reasoning.

For a quality log, record source row, rule, evidence, effect, provisional handling, and resolution owner. Example: “Ingest 3 refers to session 999; no such session is in this fixture; exclude it from trusted analysis pending source clarification; retain the raw row.” Do not create session 999 with guessed attributes or delete the raw row. The workbook asks for a simulated correction request, not an actual message to anyone.

STEP 4 OF 6

Try it yourself

Practice and checkpoint

Complete G3 before I3. Preserve the initial missingness interpretation, run the relevant queries, then explain corrections. The independent raw intake uses different IDs but the same kinds of fault; count each class separately rather than add overlapping error counts into a supposedly unique total.

Checkpoint C3 asks whether replacing every NULL with zero makes the dataset more complete. A satisfactory answer distinguishes a changed representation from new evidence, and names a measure that would become misleading. Add a quality-log.md to the cumulative project. Keep raw rows separate from admitted rows throughout the course.

Unit 3: missingness and raw quality

G3. List the missing-attendance booking IDs and their total seats. Calculate record coverage and seat coverage separately. Explain zero, NULL and no booking row using actual base IDs. Inspect intake; write three checks for duplicate claimed IDs, missing/invalid counts and absent parent sessions (the last can initially be reasoned by comparison until Unit 6). Write six quality-log entries, one per raw row, without silently adding any to trusted totals.

I3. Repeat the three check types on independent intake. Which result classes could overlap on a future row? Why is their count sum not generally a unique bad-row count? State a cautious handling rule for an identical retransmission and for conflicting records with the same identity.

C3. Evaluate “COALESCE(attended,0) completes the attendance data.” Give a case where it changes the meaning of a rate. Preserve raw evidence and identify an owner role for clarification; do not send an actual message.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Open-response practice: keep your attempt, then compare the explained answer and rubric. There is no automatic grading or submission to a teacher; review marks are not grades.

STEP 5 OF 6

Worked answer & self-check

Explained key — compare after keeping your attempt

G3 / I3 / C3: missing is not observed zero

G3: missing attendance IDs 1003 and 1007, representing 3 seats. Record coverage is 8/10=80%; seat coverage 11/14≈78.57%. Booking 1002 records zero, 1003 records NULL, session 106 has no booking. u03_quality_counts returns 10,8,2,8: total booking rows, known attendance rows, unknown rows, recorded attended seats. The final 8 is not a proven complete attendance total.

Raw log: ingest 1 and 2 both claim 9001, preserve both pending a deduplication/provenance decision; 3 points to nonexistent 999, quarantine pending authoritative session identification; 4 lacks a registration identity, do not invent one; 5 has zero reserved seats, investigate against the positive-seat rule; 6 records two attended for one booked seat, resolve the inconsistency before admission. u03_duplicate_intake returns (9001,2). u03_invalid_intake returns ingest 4,5,6. The orphan query introduced in Unit 6 returns ingest 3. None enters trusted totals.

I3: duplicate claimed identity 9101 occurs in ingest 11,12. Orphan 13 references 999. Invalid/missing-count query returns 14,15,16. In a future row a duplicate identity could also be an orphan with invalid seats; adding check counts would double-count that row. An identical retransmission may be deduplicated for an admitted view only after the identity/provenance policy is justified; retain the raw event. Conflicting claims need an authoritative correction, not automatic first/last selection.

C3: COALESCE adds no observation. Dividing known attendance by all seats after treating missing as zero implicitly asserts missing bookings had no attendance. It may serve a clearly labelled lower bound, not the measured complete rate. An acceptable owner role is the fictional attendance-record custodian; writing the role is a simulation, not a real message or secured staff assignment.

Self-review U3: complete requires distinct zero/NULL/no-row explanations, all check classes, coverage denominators and cautious handling. Partial if errors are found but silently dropped; not yet if unknown becomes asserted zero or an orphan parent is fabricated.

Saved model queries and expected fixture tables — static reference, not execution

-- Original model query; attempt workbook task before reading.
SELECT reg_id,COUNT(*) AS intake_rows FROM intake
WHERE reg_id IS NOT NULL GROUP BY reg_id HAVING COUNT(*)>1 ORDER BY reg_id;
sql-applied-course / base / u03_duplicate_intake — frozen expected output, not executed in this browser
reg_idintake_rows
90012
sql-applied-course / independent / u03_duplicate_intake — frozen expected output, not executed in this browser
reg_idintake_rows
91012
sql-applied-course / changed / u03_duplicate_intake — frozen expected output, not executed in this browser
reg_idintake_rows
No rows returned.
sql-applied-course / empty / u03_duplicate_intake — frozen expected output, not executed in this browser
reg_idintake_rows
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT ingest_id,reg_id,seats,attended FROM intake
WHERE reg_id IS NULL OR seats IS NULL OR seats<=0 OR attended<0 OR attended>seats
ORDER BY ingest_id;
sql-applied-course / base / u03_invalid_intake — frozen expected output, not executed in this browser
ingest_idreg_idseatsattended
4NULL1NULL
5900300
6900412
sql-applied-course / independent / u03_invalid_intake — frozen expected output, not executed in this browser
ingest_idreg_idseatsattended
14NULL1NULL
15910300
16910412
sql-applied-course / changed / u03_invalid_intake — frozen expected output, not executed in this browser
ingest_idreg_idseatsattended
No rows returned.
sql-applied-course / empty / u03_invalid_intake — frozen expected output, not executed in this browser
ingest_idreg_idseatsattended
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT reg_id,session_id,seats FROM registrations
WHERE attended IS NULL ORDER BY reg_id;
sql-applied-course / base / u03_missing_attendance — frozen expected output, not executed in this browser
reg_idsession_idseats
10031011
10071032
sql-applied-course / independent / u03_missing_attendance — frozen expected output, not executed in this browser
reg_idsession_idseats
20022011
sql-applied-course / changed / u03_missing_attendance — frozen expected output, not executed in this browser
reg_idsession_idseats
30033022
sql-applied-course / empty / u03_missing_attendance — frozen expected output, not executed in this browser
reg_idsession_idseats
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT COUNT(*) AS booking_rows,COUNT(attended) AS recorded_attendance_rows,
 COUNT(*)-COUNT(attended) AS unknown_attendance_rows,SUM(attended) AS recorded_attended_seats
FROM registrations;
sql-applied-course / base / u03_quality_counts — frozen expected output, not executed in this browser
booking_rowsrecorded_attendance_rowsunknown_attendance_rowsrecorded_attended_seats
10828
sql-applied-course / independent / u03_quality_counts — frozen expected output, not executed in this browser
booking_rowsrecorded_attendance_rowsunknown_attendance_rowsrecorded_attended_seats
5414
sql-applied-course / changed / u03_quality_counts — frozen expected output, not executed in this browser
booking_rowsrecorded_attendance_rowsunknown_attendance_rowsrecorded_attended_seats
3211
sql-applied-course / empty / u03_quality_counts — frozen expected output, not executed in this browser
booking_rowsrecorded_attendance_rowsunknown_attendance_rowsrecorded_attended_seats
000NULL

Compare your answer

  • Zero/NULL/no-row separated; duplicate, invalid and orphan checks; raw evidence preserved
  • Unknown asserted zero; fabricated parent; silent source deletion
  • 3 — demonstrated in this attempt: correct result and defensible reasoning, with requested evidence and transfer test.
  • 2 — partly demonstrated: central method works but a definition, control, edge case or reproduction detail is missing; revise.
  • 1 — not yet demonstrated: an important grain, missingness, denominator or execution error remains, even if one answer happens to match.
  • 0 — no assessable evidence: task absent or only a copied answer with no reasoning/attempt trail.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • U3: investigate missing, duplicate, invalid and unmatched records responsibly.

Checkpoint C3 asks whether replacing every NULL with zero makes the dataset more complete. A satisfactory answer distinguishes a changed representation from new evidence, and names a measure that would become misleading. Add a quality-log.md to the cumulative project. Keep raw rows separate from admitted rows throughout the course.

Next lesson: Unit 4 — Aggregate at the grain of the question →

LESSON 4 OF 8 · PLANNED 300 MINUTES

Unit 4 — Aggregate at the grain of the question

STEP 1 OF 6

Your objective

construct grouped summaries, reconcile them to source controls and choose defensible denominators, including empty populations.

STEP 2 OF 6

The idea

Unit 4 — Aggregate at the grain of the question

Outcome U4: construct grouped summaries, reconcile them to source controls and choose defensible denominators, including empty populations. Suggested work: five hours; unpiloted.

1. Aggregation changes what a row means

Before grouping, a registration row describes a booking. After GROUP BY session_id, each result row describes a session represented among the selected bookings. A group can contain several booking rows. You must now decide which values can be combined and what each aggregate means.

SELECT session_id,COUNT(*) AS booking_rows,SUM(seats) AS booked_seats,
       COUNT(attended) AS recorded_attendance_rows,
       SUM(attended) AS recorded_attended_seats
FROM registrations GROUP BY session_id ORDER BY session_id;

The base result is:

1. Aggregation changes what a row means — table 1
SessionBooking rowsBooked seatsRows with attendanceRecorded attended seats
1013422
1022423
1032311
1053332

There is no group for 104 or 106 because no registration row supplies those session IDs. Their absence is not a zero-valued row. Unit 6 will start with sessions and join preaggregated bookings to show every session.

The totals reconcile: booking rows 3+2+2+3=10; seats 4+4+3+3=14; known attendance rows 2+2+1+3=8; recorded attendance 2+3+1+2=8. Reconciliation catches a missing or duplicated group, but it does not by itself establish correct definitions.

2. Choose grouping fields, not accidental values

Select only group keys and aggregates in a portable, interpretable grouped query. SQLite permits some bare non-grouped columns, but their value may come from an arbitrary contributing row. A query selecting session_id,booking_ref,SUM(seats) while grouping only by session does not tell you which booking reference meaningfully represents the group. It invites a plausible-looking but unsupported label.

A common safe pattern is to aggregate bookings by session ID first, then join the resulting one-row-per-session table to session attributes. Another is to group by all requested stable dimensions. In either case state the result grain explicitly.

COUNT(*) and SUM(seats) answer different questions even when they occasionally match. One two-seat booking contributes one to the first and two to the second. Do not choose whichever measure produces the expected-looking number.

3. WHERE selects rows; HAVING selects groups

WHERE seats>=2 removes small bookings before a grouped sum. HAVING SUM(seats)>=4 keeps session groups whose total booked seats are at least four after aggregation. In base the latter retains sessions 101 and 102, each with four seats. They arrive at four through different booking counts.

To test the difference, compare a session with two one-seat bookings and a session with one two-seat booking. Both total two seats; filtering rows for seats>=2 keeps only the latter. A grouping question is not always solved by a row filter.

An SQL engine can rearrange work internally, so “before” and “after” here describe the logical result, not an instruction to measure physical execution speed.

STEP 3 OF 6

Original explanation and worked demonstration

4. An average is a numerator-denominator pair

The overall mean booking size is 14/10 = 1.4 seats per booking. It is not attendance and not a mean number of people per session. The mean of the four session booked-seat totals is 14/4 = 3.5, but that excludes the two sessions with no bookings. Over all six listed sessions it would be 14/6 ≈ 2.3333. Over only the five open sessions it would be 14/5 = 2.8. Each has a different population.

For known attendance, first restrict to bookings whose attendance is recorded, then compute attended seats divided by booked seats within that same subset:

SELECT session_id,SUM(attended) AS attended_seats,
       SUM(seats) AS known_booked_seats,
       ROUND(100.0*SUM(attended)/NULLIF(SUM(seats),0),2) AS known_attendance_pct
FROM registrations WHERE attended IS NOT NULL
GROUP BY session_id ORDER BY session_id;

The base session percentages are 66.67%,75%,100%,66.67%, with known-seat denominators 3,4,1,3. Their simple average is not the overall known-seat attendance percentage. The correct pooled ratio is (2+3+1+2)/(3+4+1+3) = 8/11 ≈ 72.73%. Weighting by the denominators would give the same pooled result; averaging rounded percentages introduces extra error.

This known-only ratio describes recorded cases, not all booked seats unless missingness assumptions are justified. Session 103's 100% is especially fragile: only one of its three booked seats has recorded attendance. A smaller denominator can make an impressive rate less informative.

5. Empty and zero are different again

Run u04_empty_summary, which selects seats>100. No supplied booking meets that condition. A scalar aggregate still returns one row: COUNT 0, SUM NULL, AVG NULL. With GROUP BY and no selected rows, there are no groups, so no result rows.

NULLIF(denominator,0) converts a zero denominator to NULL. It makes a rate explicitly unavailable instead of pretending no observations is 0% performance. Our later reporting convention may display additive totals as zero for an empty set, but a mean or rate remains unavailable. State the convention alongside the output.

STEP 4 OF 6

Try it yourself

Practice and checkpoint

Complete G4 and I4. Independently sum group outputs to source totals before viewing the key. For the October fixture, known booked seats are a different denominator from all booked seats; do not inherit September's fraction by memory.

Checkpoint C4: explain why the average of session attendance percentages can differ from the percentage obtained by pooling counts. Then show what your query returns for an empty fixture. Save group-summary.sql, its results and a denominators.md note. These are the prerequisites for the retained JOIN unit; if you cannot explain row counts versus entity counts, return to Units 1 and 3 before proceeding.

Unit 4: grouping and denominators

G4. Produce one row per represented session with booking count, booked seats, nonmissing attendance count and recorded attended seats. Reconcile every numeric column to source controls. Produce known-only attendance rates with numerator and denominator. Compare pooled rate with an unweighted average of session rates. Find sessions with at least four booked seats using HAVING. Predict a scalar aggregate and a grouped result for no qualifying bookings.

I4. Repeat the group summary and known-only rates on independent. State all-booking mean size, all-listed-session mean booked seats and open-session mean booked seats. Explain why those are different measures. Show that the denominator for the known-attendance rate is six seats, not seven and not four sessions.

C4. Explain why an unweighted average of group rates can be wrong for a pooled rate. Run the empty fixture and describe count, sum and mean without inventing a 0% result.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Open-response practice: keep your attempt, then compare the explained answer and rubric. There is no automatic grading or submission to a teacher; review marks are not grades.

STEP 5 OF 6

Worked answer & self-check

Explained key — compare after keeping your attempt

G4 / I4 / C4: what is being averaged?

G4: grouped rows are (101,3,4,2,2), (102,2,4,2,3), (103,2,3,1,1), (105,3,3,3,2) in the columns shown in Unit 4. Columns sum to 10,14,8,8. Missing session groups are not zero rows. Known-only attendance rows are 101:2/3=66.67%; 102:3/4=75%; 103:1/1=100%; 105:2/3=66.67%. Pooled 8/11=72.73%, while the unweighted mean of unrounded group rates is 77.0833…%. The latter weights a one-seat denominator as heavily as a four-seat denominator. HAVING at least four seats retains 101,102.

I4: grouped rows (201,2,2,1,1), (202,1,2,1,0), (203,2,3,2,3) reconcile to 5 bookings,7 seats,4 known-attendance rows,4 recorded attended seats. Known rates: 201:1/1=100%; 202:0/2=0%; 203:3/3=100%. Overall known-only rate 4/6=66.67%. The unweighted average also happens to be 66.67% here, an accidental agreement rather than proof of the method. Base is the counterexample. All-booking mean size 7/5=1.4; all-listed-session mean booked seats 7/4=1.75; open-session mean 7/3≈2.3333. Counts describe different entities and populations.

C4: scalar empty aggregate is one row (0,NULL,NULL) for count, sum and average; a grouped empty input yields no rows. Zero rows do not create a measured 0% rate. Weight group rates by their denominators or recompute a pooled numerator/denominator, retaining unrounded values until display.

Self-review U4: complete requires source reconciliation, actual denominators, empty behavior and a counterexample to averaging rates. Partial if group results match without explaining missing sessions; not yet if a wrong denominator or bare non-grouped label remains.

Saved model queries and expected fixture tables — static reference, not execution

-- Original model query; attempt workbook task before reading.
SELECT COUNT(*) AS booking_rows,SUM(seats) AS booked_seats,AVG(seats) AS mean_booking_size
FROM registrations WHERE seats>100;
sql-applied-course / base / u04_empty_summary — frozen expected output, not executed in this browser
booking_rowsbooked_seatsmean_booking_size
0NULLNULL
sql-applied-course / independent / u04_empty_summary — frozen expected output, not executed in this browser
booking_rowsbooked_seatsmean_booking_size
0NULLNULL
sql-applied-course / changed / u04_empty_summary — frozen expected output, not executed in this browser
booking_rowsbooked_seatsmean_booking_size
0NULLNULL
sql-applied-course / empty / u04_empty_summary — frozen expected output, not executed in this browser
booking_rowsbooked_seatsmean_booking_size
0NULLNULL
-- Original model query; attempt workbook task before reading.
SELECT session_id,SUM(seats) AS booked_seats FROM registrations
GROUP BY session_id HAVING SUM(seats)>=4 ORDER BY session_id;
sql-applied-course / base / u04_having — frozen expected output, not executed in this browser
session_idbooked_seats
1014
1024
sql-applied-course / independent / u04_having — frozen expected output, not executed in this browser
session_idbooked_seats
No rows returned.
sql-applied-course / changed / u04_having — frozen expected output, not executed in this browser
session_idbooked_seats
No rows returned.
sql-applied-course / empty / u04_having — frozen expected output, not executed in this browser
session_idbooked_seats
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT session_id,SUM(attended) AS attended_seats,SUM(seats) AS known_booked_seats,
 ROUND(100.0*SUM(attended)/NULLIF(SUM(seats),0),2) AS known_attendance_pct
FROM registrations WHERE attended IS NOT NULL GROUP BY session_id ORDER BY session_id;
sql-applied-course / base / u04_known_rates — frozen expected output, not executed in this browser
session_idattended_seatsknown_booked_seatsknown_attendance_pct
1012366.67
1023475
10311100
1052366.67
sql-applied-course / independent / u04_known_rates — frozen expected output, not executed in this browser
session_idattended_seatsknown_booked_seatsknown_attendance_pct
20111100
202020
20333100
sql-applied-course / changed / u04_known_rates — frozen expected output, not executed in this browser
session_idattended_seatsknown_booked_seatsknown_attendance_pct
3011250
sql-applied-course / empty / u04_known_rates — frozen expected output, not executed in this browser
session_idattended_seatsknown_booked_seatsknown_attendance_pct
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT session_id,COUNT(*) AS booking_rows,SUM(seats) AS booked_seats,
 COUNT(attended) AS recorded_attendance_rows,SUM(attended) AS recorded_attended_seats
FROM registrations GROUP BY session_id ORDER BY session_id;
sql-applied-course / base / u04_session_totals — frozen expected output, not executed in this browser
session_idbooking_rowsbooked_seatsrecorded_attendance_rowsrecorded_attended_seats
1013422
1022423
1032311
1053332
sql-applied-course / independent / u04_session_totals — frozen expected output, not executed in this browser
session_idbooking_rowsbooked_seatsrecorded_attendance_rowsrecorded_attended_seats
2012211
2021210
2032323
sql-applied-course / changed / u04_session_totals — frozen expected output, not executed in this browser
session_idbooking_rowsbooked_seatsrecorded_attendance_rowsrecorded_attended_seats
3012221
302120NULL
sql-applied-course / empty / u04_session_totals — frozen expected output, not executed in this browser
session_idbooking_rowsbooked_seatsrecorded_attendance_rowsrecorded_attended_seats
No rows returned.

Compare your answer

  • Grouped/source reconciliation, correct pooled fraction and empty behavior
  • Wrong denominator; unweighted rate presented as pooled; fake empty 0%
  • 3 — demonstrated in this attempt: correct result and defensible reasoning, with requested evidence and transfer test.
  • 2 — partly demonstrated: central method works but a definition, control, edge case or reproduction detail is missing; revise.
  • 1 — not yet demonstrated: an important grain, missingness, denominator or execution error remains, even if one answer happens to match.
  • 0 — no assessable evidence: task absent or only a copied answer with no reasoning/attempt trail.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • U4: aggregate and reconcile with correct denominators and empty behavior.

Checkpoint C4: explain why the average of session attendance percentages can differ from the percentage obtained by pooling counts. Then show what your query returns for an empty fixture. Save group-summary.sql, its results and a denominators.md note. These are the prerequisites for the retained JOIN unit; if you cannot explain row counts versus entity counts, return to Units 1 and 3 before proceeding.

Next lesson: Unit 5 — Preserve the entity when tables meet →

LESSON 5 OF 8 · PLANNED 240 MINUTES

Unit 5 — Preserve the entity when tables meet

STEP 1 OF 6

Your objective

predict join fan-out, preserve a measured population and reconcile results on unfamiliar and changed data.

STEP 2 OF 6

The idea

Unit 5 — Preserve the entity when tables meet

Outcome U5: predict join fan-out, preserve a measured population and reconcile results on unfamiliar and changed data. The teaching, workbook, solutions, fixtures and original verification for this unit already exist in the sibling sql-join-unit package. They are retained unchanged, not counted as a second authored unit or a new course.

Entry bridge

Units 1–4 establish the entry skills named by the original unit: SELECT, WHERE, primary/foreign keys, SUM/COUNT and GROUP BY. Recheck C1–C4 before starting. The original unit's README/workbook say earlier teaching is not included in that bounded package; this sequence supplies it by linking the packages, not by rewriting historical claims.

The case changes deliberately from workshop sessions/bookings to a community shop's orders/items. It tests whether you can transfer grain reasoning instead of memorizing column names. Order values there are whole CAD; workshop fees here are cents. Do not combine their measures or fixtures. Both are synthetic operational records, not accounting or profitability instruction.

  • 1. Read the original unit.
  • 2. Attempt its entire workbook, including independent mini-project and later-day transfer.
  • 3. Compare with explained solutions.
  • 4. Use its local execution instructions. From this package, run python3 ../sql-join-unit/run.py independent --query item_value_exists. That runner has its own fixture names and boundaries; it is not a hosted service.
  • 5. Read the public Learner readiness and assessment notice through the course's learner-notice link before continuing. Keep your own first attempt and corrections. Human subject review, learner piloting and independent assessment remain pending; self-review is not a grade or credential.

When a JOIN silently doubles your answer

The decision, not just the syntax

A fictional community shop asks for two figures: the total value of all recorded orders, and the total value of orders that have at least one recorded item. An analyst joins the order and item tables and gets a number. The query runs without an error. Is the answer trustworthy?

A successful query proves that the database understood your instructions. It does not prove that the instructions represent the question. This unit teaches you to preserve the entity being measured when a relationship produces more rows. By the end you should be able to explain table grain, predict a join, choose an order-level population, reconcile totals and averages, and demonstrate why a tempting repair fails on changed data.

All amounts here are whole CAD of pre-tax order value. They are not recognized revenue, received cash or profit. The fixtures contain no item prices, payment dates, fulfillment state, cancellations or reasons for missing records. Do not invent those facts.

1. First say what one row means

The grain of a table is the meaning of one row. In orders, one row describes one recorded order. Its primary key, order_id, uniquely identifies that order. Customer A may place several orders, so customer_id is not an order key. In order_items, one row is one recorded item row. Its primary key is item_id; its order_id refers to the parent order. Several items may refer to the same order.

Worked fixture: base

1. First say what one row means — table 1
order_idcustomer_idamount_cad
101A100
102A60
103B40
104C80
1. First say what one row means — table 2
item_idorder_id
1101
2101
3102
4103

Read the relationship aloud: order 101 has two recorded items; 102 and 103 each have one; 104 has none. “None recorded” is not an explanation. We do not know whether order 104 is unfulfilled, partially imported, cancelled, or something else.

Before executing anything, make a control total from the table at the question's grain: four recorded orders, value 100 + 60 + 40 + 80 = 280. There are three distinct customer IDs, not four customers. This check gives you something independent of the join to compare with.

Pause: Which column would you count to answer “How many recorded orders?” Why does counting customers answer a different question? Save your answer before continuing.

STEP 3 OF 6

Original explanation and worked demonstration

2. Follow a join row by row

An INNER JOIN matches each order row with each item row whose order_id is equal. Order 101 therefore appears twice. Orders 102 and 103 appear once each. Order 104 has no matching item and disappears from the result.

SELECT o.order_id,o.customer_id,o.amount_cad,i.item_id
FROM orders AS o JOIN order_items AS i ON i.order_id=o.order_id
ORDER BY o.order_id,i.item_id;
2. Follow a join row by row — table 3
order_idcustomerorder amount CADitem_id
101A1001
101A1002
102A603
103B404

The repeated 100 is the same order amount, not a second sale or the price of another item. Adding this column now produces 100 + 100 + 60 + 40 = 300. This is neither the value of all orders (280) nor the value of item-bearing orders (200). The duplicate adds 100 while the excluded order removes 80, so the net discrepancy is only 20. Opposing mistakes can partly hide one another. Even an accidentally matching total would not prove correct grain.

This expansion is often called fan-out. With a one-to-many relationship, one parent may produce several result rows. A JOIN is not inherently wrong; the expanded result is useful for inspecting items. The problem is aggregating a parent-level measure over child-level rows without preserving the parent population.

Does LEFT JOIN repair it?

A LEFT JOIN retains orders with no matching item by creating a result row whose item-side fields are NULL. It still returns two rows for order 101. The base LEFT JOIN has the four rows above plus (104, C, 80, NULL): five rows and a wrongly summed order amount of 380.

NULL in item_id means no item row matched this join. It is not an item with ID zero. The exact relationship and schema matter: our item key is non-NULL, so this NULL reliably identifies the unmatched side in this fixture.

Pause: Sketch the five LEFT JOIN rows without looking at the table. Circle the repeated order and underline the unmatched item field. A text list is as valid as a diagram.

3. Count rows, items and orders separately

On the LEFT JOIN:

SELECT COUNT(*) AS joined_rows,
       COUNT(i.item_id) AS matched_items,
       COUNT(DISTINCT o.order_id) AS distinct_orders
FROM orders AS o LEFT JOIN order_items AS i ON i.order_id=o.order_id;

The result is 5 joined rows, 4 matched item IDs, 4 distinct orders. COUNT(*) counts the unmatched output row. COUNT(i.item_id) excludes its NULL item key. COUNT(DISTINCT o.order_id) counts each order identifier once. On this base INNER JOIN the corresponding counts are 4, 4 and 3.

To display the number of recorded items for every order, group at order grain and count the non-NULL child key:

SELECT o.order_id,COUNT(i.item_id) AS item_rows
FROM orders AS o LEFT JOIN order_items AS i ON i.order_id=o.order_id
GROUP BY o.order_id ORDER BY o.order_id;

The counts are 101→2, 102→1, 103→1, 104→0. Substituting COUNT(*) would report one output row for order 104, not one real item. Explain what each count represents rather than treating COUNT variants as interchangeable.

4. Let the question select the repair

All recorded order value: no join is needed. The order table already has exactly one row per entity being measured.

SELECT SUM(amount_cad) AS total_cad FROM orders;

This gives 280.

Value of orders with at least one recorded item: keep one row per order but test whether a matching item exists.

SELECT SUM(o.amount_cad) AS total_cad
FROM orders AS o
WHERE EXISTS (
  SELECT 1 FROM order_items AS i WHERE i.order_id=o.order_id
);

For each outer order, the subquery asks whether at least one matching item row can be found. SELECT 1 supplies an arbitrary constant: EXISTS cares about whether a row exists, not whether that constant equals an amount. Two matching item rows still cause the outer order to be included only once. Orders 101, 102 and 103 contribute 200.

An equivalent approach reduces the item table to one row per order key before joining:

SELECT SUM(o.amount_cad) AS total_cad
FROM orders AS o
JOIN (SELECT DISTINCT order_id FROM order_items) AS present
  ON present.order_id=o.order_id;

DISTINCT here removes repeated identities from the child side. It does not merge two orders merely because their amounts happen to be equal. The resulting relation contains one row per included order.

Why SUM(DISTINCT amount_cad) is not a general repair

On the base INNER JOIN, the distinct amount values are 100, 60 and 40, which sum to 200. That happens to equal the desired item-bearing total. But the reasoning is wrong: identical amounts do not identify identical orders.

Reset to the separate equal fixture. It adds order 105, customer D, amount 100, plus item 5 belonging to that order. These are two distinct CAD 100 orders, 101 and 105. Item-bearing order value is now 300, but SUM(DISTINCT amount_cad) still returns 200 because it keeps the number 100 only once. A counterexample exposes the bug that the original fixture concealed.

COUNT(DISTINCT order_id) can repair an entity count. It cannot repair the rows passed to a separate SUM. A query containing both a correct distinct count and an uncorrected amount sum can still be wrong.

5. An average inherits its population

For all recorded orders, AVG(amount_cad) on orders gives 280 / 4 = 70. For item-bearing orders, applying the same EXISTS filter gives 200 / 3 = 66.666…, reported as CAD 66.67, rounded to cents. Keep the unrounded number during comparisons.

The raw INNER JOIN average is 300 / 4 = 75. It gives order 101 two contributions because it has two items. This is not the mean per unique order. Dividing a correct total by the wrong count is another way to create an incorrect average.

Our amount_cad field is required and includes zero values. In the independent fixture, a genuine zero-valued order must still count in an order mean. In SQLite, AVG ignores NULL inputs; do not equate missing values with zero. If no order meets a filter, SUM and AVG return NULL in this exercise, while COUNT returns zero. An empty population has no defined mean. A deliberate presentation rule may display a zero total for no transactions, but it must not silently turn “no observations” into a zero average.

6. Missing parents and missing children are different

Order 104 with no item is a missing-child case. The base foreign key permits an order to have no items, but it does not permit an item to refer to a nonexistent order. The separate staging fixture models raw, not-yet-validated incoming item rows. One staging row has item_id=9, order_id=999, for which no parent exists.

SELECT s.item_id,s.order_id
FROM staging_items AS s LEFT JOIN orders AS o ON o.order_id=s.order_id
WHERE o.order_id IS NULL
ORDER BY s.item_id;

The query returns (9,999). It identifies the offending record, not the reason it happened. Do not delete it or invent a parent automatically. Preserve the raw row, document the mismatch and request an authoritative correction through the fictional case's process. Our executable test also confirms that inserting that row directly into the constrained order_items table is rejected.

7. A repeatable reconciliation routine

Before sharing an answer, record:

  • 1. The question and population: all recorded orders or those with recorded items?
  • 2. Each table's grain, primary key and relationship.
  • 3. Source counts and a parent-grain control total.
  • 4. Predicted join row counts, then actual rows and unmatched IDs.
  • 5. Correct aggregation, count/denominator, units and rounding.
  • 6. At least one changed-data test, especially equal values or no matches.
  • 7. What the data cannot establish and which follow-up evidence is needed.

Now close this worked example and attempt the independent fixture in the workbook. Retain your first query, the observed discrepancy and the reason for your correction. The point is not to memorize 280; it is to know why a plausible answer may be wrong and how to demonstrate a correct one on new data.

Source note

SQL behavior was checked against SQLite's SELECT documentation, aggregate functions, and foreign-key support, accessed 31 October 2026. Explanations, independent cases and practice are newly authored for this unit; the worked fixture follows the user's supplied P brief. These links are references, not required accounts or copied lessons.

STEP 4 OF 6

Try it yourself

Exit bridge: apply the mechanism, not the numbers

The original base INNER JOIN repeats order 101's amount because two items match. In the workshop base, joining sessions to bookings repeats session 101's capacity three times. Capacity remains six, not eighteen. A LEFT JOIN also retains sessions with no bookings; that does not remove repeated capacity for sessions that do have bookings.

Before Unit 6, write answers to these transfer questions:

  • What is the result grain of a raw session–registration join?
  • Why does COUNT of the child key differ from COUNT(*) for an unmatched session?
  • Would SUM(DISTINCT capacity) repair the capacity sum when two different sessions both have capacity four?
  • How can preaggregating bookings to one row per session make a join safe for session-level reporting?

JOIN reconciliation workbook

Your name or initials (optional): __________ Date: __________

Keep answers locally. Use fictional records only. You may use text lists instead of drawing. Save your initial prediction before execution and explain every revision. The answer pack is separate: SOLUTIONS.md.

A. Readiness check (before starting)

Explain in your own words: a table row; a primary key; a GROUP BY result; SUM versus COUNT; why 0 and NULL differ. Write a SELECT that reads order IDs and amounts without joining. If you cannot yet do these, return to earlier SQL teaching rather than guessing through this unit. No earlier SQL unit is included here.

B. Guided base case

Use only base. The complete records are in UNIT.md and data/base.sql.

G1. Grain and keys. Write one sentence defining a row in each table. Identify primary and foreign keys. Explain whether customer_id uniquely identifies an order.

Initial answer: __________

Correction and reason: __________

G2. Predict expansion. Without running SQL, list every INNER JOIN result as (order_id,item_id). Then list every LEFT JOIN result. Predict each row count and identify any parent repeated or excluded. Run inner_rows/left_rows only afterwards.

Prediction: __________ Observed: __________ Why: __________

G3. Diagnose totals. Write an all-order sum query and compare it with raw inner/left joined sums. Reconcile differences by naming exactly which order values were repeated and omitted. Why would matching one expected total not, by itself, prove the method?

Queries and reconciliation: __________

G4. Three counts. Predict COUNT(*), COUNT(i.item_id) and COUNT(DISTINCT o.order_id) for each join. Explain why the results answer different questions. Then produce one row per order with its number of recorded items, including orders with none.

Predictions, SQL and meanings: __________

G5. Match the question. Write one query for all recorded order value and two equivalent queries for the value of orders with at least one recorded item. At least one should use EXISTS. Explain why two matches do not give two outer contributions.

SQL and explanation: __________

G6. Denominators. Compute the all-order mean and the item-bearing mean. State numerator, denominator, unit and rounding. Diagnose the raw INNER JOIN mean.

Answer: __________

C. Counterexample and data-quality extensions

E1. Equal values. Reset by selecting equal (not base). This is base plus order (105,D,100) and item (5,105). Compare the correct all-order value, correct item-bearing value, raw inner/left sums and SUM(DISTINCT amount_cad). Explain why equal numbers do not mean the same entity. Does adding a correct COUNT(DISTINCT order_id) alongside a wrong SUM repair the SUM?

Initial prediction: __________ Observed: __________ Explanation: __________

E2. Orphan input. Reset to staging. Inspect the raw staging row (9,999). Write a query identifying staging items with no parent order. Contrast this with an order having no items. Recommend a cautious handling step without inventing a reason or silently discarding evidence.

SQL, interpretation and action: __________

D. Independent case: a different community stall

Use only independent. Do not modify or combine it with the base fixture.

D. Independent case: a different community stall — table 1
order_idcustomer_idamount_cad
201D50
202E50
203D25
204F0
205G75
D. Independent case: a different community stall — table 2
item_idorder_id
11201
12201
13202
14204
15204
16204

I1. Counts before execution. Predict the inner/left output rows, distinct matched orders, matched item rows and all-order count. Identify every order without a recorded item.

Prediction: __________ Observed: __________ Correction: __________

I2. Values and means. Write correct queries for all-order value, item-bearing value and both means. Compare both raw joined sums and SUM(DISTINCT amount_cad). Explain the role of the zero-valued order and the two equal-valued orders. Retain unrounded means in your working.

SQL/result/reason: __________

I3. Empty populations. Predict what each of SUM, COUNT and AVG should show if there are no matching orders. Explain why a reporting choice to display total zero is not a reason to report mean zero. This is a reasoning task; the supplied automated suite checks empty/no-item cases without requiring you to modify data.

Answer: __________

E. Mini-project: a reconciliation note

A fictional coordinator wants: (a) all recorded order value; (b) value and mean for orders with recorded items; (c) IDs needing item-record follow-up. They have proposed summing order amounts after a LEFT JOIN. Use the independent fixture.

Create a concise one-page note plus your .sql files and results. Include:

  • The exact population for each requested measure, table grain and relationship.
  • Their faulty query/result and corrected queries/results.
  • An entity-level reconciliation, including zero/equal amounts and missing child rows.
  • Numerator/denominator/rounding for each mean.
  • A changed-data test that would expose a plausible but wrong repair.
  • At least three limits of the records and a cautious follow-up request.
  • Fixture name, runtime version if executed, reproduction command and correction log.

Do not claim recognized revenue, profits, payment, fulfillment or reasons for missing items. Equivalent SQL is acceptable if it preserves the required population. A short accurate note is better than filling a word quota.

E. Mini-project: a reconciliation note — table 3
CriterionWeightEvidence needed
Grain and relationship25Correct entities/keys; expansion and missing-match explanation
Queries and outputs30Correct populations, totals, means; executable/reproducible answer
Reconciliation and limits25Specific wrong-result explanation, counterexample, justified limits
Reproducibility and communication20Fixture/version/queries/results, clear note, visible revisions

Self-check bands: complete = correct result plus valid reasoning and evidence; partial = some correct outputs but missing population or reproducibility; not yet = fan-out/denominator error remains. Syntax alone cannot earn full correctness. No external marking service is implied.

F. Delayed transfer (later day, first attempt without solutions)

Use delayed. Orders: (301,H,30), (302,I,90), (303,J,30). Items: (21,301), (22,302), (23,302).

D1. Predict counts and faulty inner/left sums; produce correct totals and means. Explain why a DISTINCT-amount shortcut may look successful for one requested measure but fail for another. Identify the missing-child order without inventing a cause.

D2. Write a five-sentence verification checklist for a future dataset with a different number of items per order. Mark which checks concern SQL execution and which concern interpretation. Compare your first attempt against the key, then explain one durable rule you will use again.

Date / initial answer / later correction: __________

Unit 5: retained JOIN lab

Read units/05-join-bridge.md, then complete all G/E/I/project/D tasks in ../sql-join-unit/WORKBOOK.md. Keep its fixture names separate from this package. Bring back a short note explaining how repeated order value corresponds to repeated session capacity. Do not retype or revise the existing unit or overwrite its evidence.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Open-response practice: keep your attempt, then compare the explained answer and rubric. There is no automatic grading or submission to a teacher; review marks are not grades.

STEP 5 OF 6

Worked answer & self-check

Explained key — compare after keeping your attempt

Bridge key: raw joined rows are session–booking matches, plus one unmatched output row per childless session for a LEFT JOIN. A non-NULL child key counts actual matches; COUNT(*) counts the unmatched output row too. DISTINCT capacity merges different sessions with equal capacity and is not an entity repair. Grouping bookings by session ID creates at most one summary row per parent, so joining that summary preserves one row per session. It still requires an explicit policy for missing versus zero summary values.

Your Unit 5 work is the sequence's retained join-query lab evidence. Do not substitute this bridge paragraph for the full worked explanation, independent case or delayed task. The four-hour suggestion is an unpiloted estimate already attached to the bounded unit, included once in the sequence's workload range.

Explained answers and project review

Attempt WORKBOOK.md first. These are self-check models, not evidence that an instructor has marked your work. Equivalent SQL is acceptable when it answers the same question, handles the counterexamples and can be reproduced. All values are whole CAD order values unless a mean is explicitly rounded.

Readiness

A primary key identifies one row; grouping combines rows that share the chosen grouping values. SUM adds numerical values, while COUNT counts rows or non-NULL expressions. A zero amount is a recorded number, not missing information. A starting query is SELECT order_id,amount_cad FROM orders ORDER BY order_id;. If this is unfamiliar, the earlier SQL sequence is a real prerequisite, not supplied by this unit.

Guided base case

G1. Grain and keys

orders is one row per recorded order, identified by order_id. order_items is one row per recorded item, identified by item_id; its order_id refers to the parent. Customer A appears in two different orders, so customer_id is not the order key. One order can match many item rows. The fixture has no item price or quantity column, so item-row counts are not monetary subtotals or inferred product quantities.

G2. Exact expansion

INNER JOIN pairs: (101,1), (101,2), (102,3), (103,4) — 4 rows. LEFT JOIN adds (104,NULL) — 5 rows. Order 101 is repeated; order 104 is absent from the inner result. Executable answers: inner_rows.sql, left_rows.sql. Their explicit ORDER BY makes inspection reproducible; SQL does not otherwise promise this display order.

G3. Totals and cancellation of errors

G3. Totals and cancellation of errors — table 1
Question/methodResult CADExplanation
All orders, sum directly from orders280100+60+40+80
Raw inner joined sum (wrong for either requested order total)300100+100+60+40
Raw left joined sum (wrong all-order total)380100+100+60+40+80
Orders with at least one item, correct200100+60+40

Relative to all-order value, the inner mistake adds 100 by repeating order 101 and subtracts 80 by excluding order 104: 280+100−80=300. The left mistake only adds the repeated 100: 280+100=380. A plausible number is not a grain check; two errors could cancel exactly on a different dataset.

Queries: all_value.sql, inner_wrong_value.sql, left_wrong_value.sql. Files with wrong are intentional diagnostic examples, clearly labelled; they must not be presented as correct recommended queries.

G4. Counts and zero children

G4. Counts and zero children — table 2
JoinCOUNT(*)COUNT(i.item_id)COUNT(DISTINCT o.order_id)
Inner443
Left544

The LEFT JOIN placeholder for 104 contributes to COUNT(*) but not COUNT(i.item_id). Distinct parent IDs answer the entity count. join_counts.sql is the left-join version; replacing LEFT JOIN with INNER JOIN gives the other row.

per_order_counts.sql produces (101,2),(102,1),(103,1),(104,0). COUNT(*) inside this grouping would incorrectly suggest one recorded item for 104. Counting a required child key, not a placeholder row, avoids that mistake.

G5. Correct populations

All recorded order value uses all_value.sql and no join. Item-bearing order value uses item_value_exists.sql, or item_value_distinct_keys.sql. Both return 200. The EXISTS expression decides whether to keep each order, not how often to copy it. The deduplicated-key alternative reduces the child side to order IDs 101, 102 and 103 before matching. It deduplicates identities, not amounts.

G6. Means

All orders: numerator 280, denominator 4, 70 CAD per recorded order. Item-bearing orders: numerator 200, denominator 3, 66.666… CAD, reported as 66.67 rounded to cents. The INNER JOIN mean is 300/4=75; it gives order 101 double weight. Queries: all_mean.sql, item_mean.sql, inner_wrong_mean.sql. Reporting “average order value” without the population leaves an important ambiguity.

Extension answers

E1. Equal values are not equal identities (equal only)

E1. Equal values are not equal identities (equal only) — table 3
MeasureCAD
Correct all-order total380
Correct item-bearing total300
Raw inner joined sum400
Raw left joined sum480
SUM(DISTINCT amount_cad) on the inner join200

The fifth order adds a distinct parent worth 100 and one matching item. The correct item-bearing population is now four orders: 101,102,103,105. SUM(DISTINCT amount_cad) sees only values 100,60,40 and loses order 105's separate contribution. Adding a correct COUNT(DISTINCT order_id) in the same SELECT does not change the SUM input. distinct_amount_wrong.sql demonstrates the defect; the automated negative controls require this method to disagree with the correct answer on this fixture.

E2. Orphan versus missing child (staging only)

staging_orphans.sql returns (item_id=9, order_id=999). That raw item has no matching parent. By contrast, no_item_orders.sql finds order 104, which exists but lacks recorded items. Keep the unvalidated staging row and its source provenance for investigation; seek the authoritative order identifier or correction before accepting it. Do not silently invent order 999, discard the item, or explain 104 as “unfulfilled.” In this fixture the constrained item table refuses an orphan; raw staging is intentionally unconstrained to let you diagnose an incoming defect.

Independent case answers

I1. Counts and missing children

Order 201 repeats twice, 202 once and 204 three times: 6 inner rows, representing 3 item-bearing orders. Orders 203 and 205 each add an unmatched placeholder to the LEFT JOIN: 8 left rows. The left output contains 6 non-NULL item keys and 5 distinct order IDs. Missing-child IDs are 203 and 205. The zero value on 204 does not make its three item records disappear.

I2. Correct and faulty values

I2. Correct and faulty values — table 4
MeasureIndependent result
All-order total200 CAD
Item-bearing total100 CAD
Raw INNER JOIN sum150 CAD
Raw LEFT JOIN sum250 CAD
SUM(DISTINCT amount_cad) on inner join50 CAD
All-order mean40 CAD
Item-bearing mean100/3 CAD = 33.33 rounded

Check by entities: all orders are 50+50+25+0+75=200. Item-bearing orders 201,202,204 contribute 50+50+0=100. The inner sum is 50+50+50+0+0+0=150. The left sum adds 25+75=100 to reach 250. Distinct amount values among matched rows are 50 and 0, so the shortcut returns 50, losing a real equal-value order. The zero-valued order belongs in the denominator: item-bearing mean divides by three, not two. Deleting zero values to increase the mean would answer a different question.

Use the same correct named queries with fixture independent; their code should not contain the fixture's expected amounts or hard-coded order IDs. An answer that only returns literal 200 is not an analysis.

I3. Empty and no-match cases

With an empty order table: COUNT(*) is 0, SUM(amount_cad) is NULL and AVG(amount_cad) is NULL in SQLite. With four base orders but no items, the all-order total remains 280; the item-bearing filtered population is empty, so its SUM/AVG are NULL. The LEFT JOIN has four rows, zero matched item IDs and four distinct orders. NULL does not say the mean is zero. If the reporting contract requires a zero displayed transaction total for an empty population, document the conversion separately and retain an undefined mean. No such conversion is silently applied by these answer queries.

Mini-project model (independent fixture)

Reconciliation note — fictional community stall. The five recorded orders total CAD 200. The three orders with at least one recorded item (201,202,204) total CAD 100 and average CAD 33.33 per item-bearing order, rounded from 100/3. Across all five orders, the mean is CAD 40. I used the order table for all-order measures and an EXISTS filter for item-bearing measures so every included order contributes once.

The proposed LEFT JOIN sum is CAD 250 because order 201's CAD 50 amount is included twice. Its eight output rows are six recorded item matches plus placeholders for orders 203 and 205. Order 204 has three item rows but amount zero; it still counts as one order in the item-bearing mean. SUM(DISTINCT amount_cad) is not a safe repair: orders 201 and 202 are different orders with equal values, and that shortcut gives only CAD 50 for the matched population.

Orders 203 and 205 need item-record follow-up. No item prices, payments, fulfillment states or missing-record causes are supplied, so these numbers do not establish recognized revenue, cash collected, profit, items sold or fulfillment. Please check the authoritative source for the missing item links before explaining them. Preserve the raw records and document any correction.

Attach query files and actual command outputs, not just this prose. A reproduction log should name independent, the engine version actually used, the exact query path and the first incorrect/corrected result. One acceptable changed-data test is the equal fixture; another is adding a new matched order with an existing amount and confirming that the correct total rises by that amount while the DISTINCT-amount method does not.

Applying the rubric honestly

Grain/relationship (25): full evidence states both keys, one-to-many expansion and missing-child interpretation. Merely writing “duplicates” without identifying what repeats is partial.
Correct queries/outputs (30): full evidence preserves both populations, includes zero orders in means, shows execution or honestly labels paper tracing, and reproduces results. A correct value obtained by a method that fails the equal-value case cannot earn full correctness.
Reconciliation/limits (25): full evidence accounts for 250 versus 200, explains the counterexample and avoids invented causes or accounting claims.
Reproducibility/communication (20): full evidence includes fixture, SQL, output, runtime if executed and correction reasons. Clear equivalent SQL is acceptable. An unsupported claim of running the code is not evidence.

These are analytic self-review criteria, not a validated grading instrument or a promise of recognized assessment. A reviewer may accept a different well-supported note.

Delayed transfer

D1: INNER JOIN pairs are (301,21),(302,22),(302,23) — 3 rows. LEFT JOIN adds (303,NULL) — 4 rows. Correct all-order total is 150, correct item-bearing total 120, raw inner sum 210, raw left sum 240. All-order mean is 50; item-bearing mean is 60. Order 303 lacks a recorded item. SUM(DISTINCT amount_cad) happens to give 120 for the matched population here, but applying it to all orders still gives 120 rather than 150, because orders 301 and 303 share amount 30. One successful case cannot establish a general repair.

D2 example checklist: define the population and measure; inspect row grain/keys; predict and inspect join expansion; reconcile entity-level totals/counts and denominators; test equal values/no matches and state data limits. Execution checks show the query runs and returns the intended row structure; interpretation checks establish whether the population, measures and conclusions match the actual question. A good correction explains a rule such as “deduplicate by entity key before adding an entity-level measure,” not just replacing one memorized number.

Saved model queries and expected fixture tables — static reference, not execution

SELECT AVG(amount_cad) AS mean_cad FROM orders;
sql-join-unit / base / all_mean — frozen expected output, not executed in this browser
mean_cad
70
sql-join-unit / equal / all_mean — frozen expected output, not executed in this browser
mean_cad
76
sql-join-unit / independent / all_mean — frozen expected output, not executed in this browser
mean_cad
40
sql-join-unit / delayed / all_mean — frozen expected output, not executed in this browser
mean_cad
50
sql-join-unit / staging / all_mean — frozen expected output, not executed in this browser
mean_cad
70
SELECT SUM(amount_cad) AS total_cad FROM orders;
sql-join-unit / base / all_value — frozen expected output, not executed in this browser
total_cad
280
sql-join-unit / equal / all_value — frozen expected output, not executed in this browser
total_cad
380
sql-join-unit / independent / all_value — frozen expected output, not executed in this browser
total_cad
200
sql-join-unit / delayed / all_value — frozen expected output, not executed in this browser
total_cad
150
sql-join-unit / staging / all_value — frozen expected output, not executed in this browser
total_cad
280
SELECT customer_id,COUNT(*) AS order_count,SUM(amount_cad) AS total_cad,
       AVG(amount_cad) AS mean_cad
FROM orders GROUP BY customer_id ORDER BY customer_id;
sql-join-unit / base / customer_summary — frozen expected output, not executed in this browser
customer_idorder_counttotal_cadmean_cad
A216080
B14040
C18080
sql-join-unit / equal / customer_summary — frozen expected output, not executed in this browser
customer_idorder_counttotal_cadmean_cad
A216080
B14040
C18080
D1100100
sql-join-unit / independent / customer_summary — frozen expected output, not executed in this browser
customer_idorder_counttotal_cadmean_cad
D27537.5
E15050
F100
G17575
sql-join-unit / delayed / customer_summary — frozen expected output, not executed in this browser
customer_idorder_counttotal_cadmean_cad
H13030
I19090
J13030
sql-join-unit / staging / customer_summary — frozen expected output, not executed in this browser
customer_idorder_counttotal_cadmean_cad
A216080
B14040
C18080
-- Deliberate mistake: equal amounts are not the same order.
SELECT SUM(DISTINCT o.amount_cad) AS wrongly_deduplicated_cad
FROM orders AS o JOIN order_items AS i ON i.order_id=o.order_id;
sql-join-unit / base / distinct_amount_wrong — frozen expected output, not executed in this browser
wrongly_deduplicated_cad
200
sql-join-unit / equal / distinct_amount_wrong — frozen expected output, not executed in this browser
wrongly_deduplicated_cad
200
sql-join-unit / independent / distinct_amount_wrong — frozen expected output, not executed in this browser
wrongly_deduplicated_cad
50
sql-join-unit / delayed / distinct_amount_wrong — frozen expected output, not executed in this browser
wrongly_deduplicated_cad
120
sql-join-unit / staging / distinct_amount_wrong — frozen expected output, not executed in this browser
wrongly_deduplicated_cad
200
SELECT o.order_id,o.customer_id,o.amount_cad,i.item_id
FROM orders AS o INNER JOIN order_items AS i ON i.order_id=o.order_id
ORDER BY o.order_id,i.item_id;
sql-join-unit / base / inner_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
101A1001
101A1002
102A603
103B404
sql-join-unit / equal / inner_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
101A1001
101A1002
102A603
103B404
105D1005
sql-join-unit / independent / inner_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
201D5011
201D5012
202E5013
204F014
204F015
204F016
sql-join-unit / delayed / inner_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
301H3021
302I9022
302I9023
sql-join-unit / staging / inner_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
101A1001
101A1002
102A603
103B404
-- Deliberate mistake: this averages joined item rows, not unique orders.
SELECT AVG(o.amount_cad) AS wrongly_weighted_mean_cad
FROM orders AS o JOIN order_items AS i ON i.order_id=o.order_id;
sql-join-unit / base / inner_wrong_mean — frozen expected output, not executed in this browser
wrongly_weighted_mean_cad
75
sql-join-unit / equal / inner_wrong_mean — frozen expected output, not executed in this browser
wrongly_weighted_mean_cad
80
sql-join-unit / independent / inner_wrong_mean — frozen expected output, not executed in this browser
wrongly_weighted_mean_cad
25
sql-join-unit / delayed / inner_wrong_mean — frozen expected output, not executed in this browser
wrongly_weighted_mean_cad
70
sql-join-unit / staging / inner_wrong_mean — frozen expected output, not executed in this browser
wrongly_weighted_mean_cad
75
-- Deliberate mistake for diagnosis: order amount repeats for each matching item.
SELECT SUM(o.amount_cad) AS wrongly_summed_cad
FROM orders AS o INNER JOIN order_items AS i ON i.order_id=o.order_id;
sql-join-unit / base / inner_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
300
sql-join-unit / equal / inner_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
400
sql-join-unit / independent / inner_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
150
sql-join-unit / delayed / inner_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
210
sql-join-unit / staging / inner_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
300
SELECT AVG(o.amount_cad) AS mean_cad FROM orders AS o
WHERE EXISTS (SELECT 1 FROM order_items AS i WHERE i.order_id=o.order_id);
sql-join-unit / base / item_mean — frozen expected output, not executed in this browser
mean_cad
66.66666666666667
sql-join-unit / equal / item_mean — frozen expected output, not executed in this browser
mean_cad
75
sql-join-unit / independent / item_mean — frozen expected output, not executed in this browser
mean_cad
33.333333333333336
sql-join-unit / delayed / item_mean — frozen expected output, not executed in this browser
mean_cad
60
sql-join-unit / staging / item_mean — frozen expected output, not executed in this browser
mean_cad
66.66666666666667
SELECT SUM(o.amount_cad) AS total_cad
FROM orders AS o
JOIN (SELECT DISTINCT order_id FROM order_items) AS present
  ON present.order_id=o.order_id;
sql-join-unit / base / item_value_distinct_keys — frozen expected output, not executed in this browser
total_cad
200
sql-join-unit / equal / item_value_distinct_keys — frozen expected output, not executed in this browser
total_cad
300
sql-join-unit / independent / item_value_distinct_keys — frozen expected output, not executed in this browser
total_cad
100
sql-join-unit / delayed / item_value_distinct_keys — frozen expected output, not executed in this browser
total_cad
120
sql-join-unit / staging / item_value_distinct_keys — frozen expected output, not executed in this browser
total_cad
200
SELECT SUM(o.amount_cad) AS total_cad
FROM orders AS o
WHERE EXISTS (SELECT 1 FROM order_items AS i WHERE i.order_id=o.order_id);
sql-join-unit / base / item_value_exists — frozen expected output, not executed in this browser
total_cad
200
sql-join-unit / equal / item_value_exists — frozen expected output, not executed in this browser
total_cad
300
sql-join-unit / independent / item_value_exists — frozen expected output, not executed in this browser
total_cad
100
sql-join-unit / delayed / item_value_exists — frozen expected output, not executed in this browser
total_cad
120
sql-join-unit / staging / item_value_exists — frozen expected output, not executed in this browser
total_cad
200
SELECT COUNT(*) AS joined_rows, COUNT(i.item_id) AS matched_items,
       COUNT(DISTINCT o.order_id) AS distinct_orders
FROM orders AS o LEFT JOIN order_items AS i ON i.order_id=o.order_id;
sql-join-unit / base / join_counts — frozen expected output, not executed in this browser
joined_rowsmatched_itemsdistinct_orders
544
sql-join-unit / equal / join_counts — frozen expected output, not executed in this browser
joined_rowsmatched_itemsdistinct_orders
655
sql-join-unit / independent / join_counts — frozen expected output, not executed in this browser
joined_rowsmatched_itemsdistinct_orders
865
sql-join-unit / delayed / join_counts — frozen expected output, not executed in this browser
joined_rowsmatched_itemsdistinct_orders
433
sql-join-unit / staging / join_counts — frozen expected output, not executed in this browser
joined_rowsmatched_itemsdistinct_orders
544
SELECT o.order_id,o.customer_id,o.amount_cad,i.item_id
FROM orders AS o LEFT JOIN order_items AS i ON i.order_id=o.order_id
ORDER BY o.order_id,i.item_id;
sql-join-unit / base / left_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
101A1001
101A1002
102A603
103B404
104C80NULL
sql-join-unit / equal / left_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
101A1001
101A1002
102A603
103B404
104C80NULL
105D1005
sql-join-unit / independent / left_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
201D5011
201D5012
202E5013
203D25NULL
204F014
204F015
204F016
205G75NULL
sql-join-unit / delayed / left_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
301H3021
302I9022
302I9023
303J30NULL
sql-join-unit / staging / left_rows — frozen expected output, not executed in this browser
order_idcustomer_idamount_caditem_id
101A1001
101A1002
102A603
103B404
104C80NULL
-- Deliberate mistake: preserving unmatched orders does not remove fan-out.
SELECT SUM(o.amount_cad) AS wrongly_summed_cad
FROM orders AS o LEFT JOIN order_items AS i ON i.order_id=o.order_id;
sql-join-unit / base / left_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
380
sql-join-unit / equal / left_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
480
sql-join-unit / independent / left_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
250
sql-join-unit / delayed / left_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
240
sql-join-unit / staging / left_wrong_value — frozen expected output, not executed in this browser
wrongly_summed_cad
380
SELECT o.order_id,o.customer_id,o.amount_cad
FROM orders AS o
WHERE NOT EXISTS (SELECT 1 FROM order_items AS i WHERE i.order_id=o.order_id)
ORDER BY o.order_id;
sql-join-unit / base / no_item_orders — frozen expected output, not executed in this browser
order_idcustomer_idamount_cad
104C80
sql-join-unit / equal / no_item_orders — frozen expected output, not executed in this browser
order_idcustomer_idamount_cad
104C80
sql-join-unit / independent / no_item_orders — frozen expected output, not executed in this browser
order_idcustomer_idamount_cad
203D25
205G75
sql-join-unit / delayed / no_item_orders — frozen expected output, not executed in this browser
order_idcustomer_idamount_cad
303J30
sql-join-unit / staging / no_item_orders — frozen expected output, not executed in this browser
order_idcustomer_idamount_cad
104C80
SELECT o.order_id,COUNT(i.item_id) AS item_rows
FROM orders AS o LEFT JOIN order_items AS i ON i.order_id=o.order_id
GROUP BY o.order_id ORDER BY o.order_id;
sql-join-unit / base / per_order_counts — frozen expected output, not executed in this browser
order_iditem_rows
1012
1021
1031
1040
sql-join-unit / equal / per_order_counts — frozen expected output, not executed in this browser
order_iditem_rows
1012
1021
1031
1040
1051
sql-join-unit / independent / per_order_counts — frozen expected output, not executed in this browser
order_iditem_rows
2012
2021
2030
2043
2050
sql-join-unit / delayed / per_order_counts — frozen expected output, not executed in this browser
order_iditem_rows
3011
3022
3030
sql-join-unit / staging / per_order_counts — frozen expected output, not executed in this browser
order_iditem_rows
1012
1021
1031
1040
SELECT s.item_id,s.order_id FROM staging_items AS s
LEFT JOIN orders AS o ON o.order_id=s.order_id
WHERE o.order_id IS NULL ORDER BY s.item_id;
sql-join-unit / staging / staging_orphans — frozen expected output, not executed in this browser
item_idorder_id
9999

Compare your answer

  • Retained unit independent project, key-level fan-out explanation, equal-value and empty counterexamples
  • SUM DISTINCT values used as general entity repair; unmatched records ignored
  • 3 — demonstrated in this attempt: correct result and defensible reasoning, with requested evidence and transfer test.
  • 2 — partly demonstrated: central method works but a definition, control, edge case or reproduction detail is missing; revise.
  • 1 — not yet demonstrated: an important grain, missingness, denominator or execution error remains, even if one answer happens to match.
  • 0 — no assessable evidence: task absent or only a copied answer with no reasoning/attempt trail.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • U5: preserve entity populations across joins and demonstrate counterexamples.

Your Unit 5 work is the sequence's retained join-query lab evidence. Do not substitute this bridge paragraph for the full worked explanation, independent case or delayed task. The four-hour suggestion is an unpiloted estimate already attached to the bounded unit, included once in the sequence's workload range.

Next lesson: Unit 6 — Build an analysis in inspectable stages →

LESSON 6 OF 8 · PLANNED 360 MINUTES

Unit 6 — Build an analysis in inspectable stages

STEP 1 OF 6

Your objective

use CASE, subqueries and common-table expressions to express rules while preserving grain and missingness.

STEP 2 OF 6

The idea

Unit 6 — Build an analysis in inspectable stages

Outcome U6: use CASE, subqueries and common-table expressions to express rules while preserving grain and missingness. Suggested work: six hours with independent tasks, unpiloted.

1. Name categories without concealing unknowns

A coordinator wants to distinguish complete, partial, zero and unrecorded attendance. A CASE expression assigns an output value using ordered conditions:

SELECT reg_id,
 CASE WHEN attended IS NULL THEN 'unknown'
      WHEN attended=0 THEN 'none recorded'
      WHEN attended<seats THEN 'partial'
      ELSE 'all recorded' END AS attendance_band
FROM registrations ORDER BY reg_id;

CASE uses the first true branch. Test unknown first because missing comparisons do not behave like ordinary numbers. Then separate observed zero from partial attendance. The final ELSE is safe for this constrained source, where a nonmissing attendance count cannot be negative or above seats. Applying it to raw intake would mislabel invalid rows; an input contract matters.

For base, 1003 and 1007 are unknown; 1002 and 1009 have none recorded; 1004 is partial (one of two); the remaining five are all recorded. The labels describe supplied counts, not motivations or causes. Do not rename “none recorded” to “uninterested.”

CASE also supports conditional totals. SUM(CASE WHEN attended IS NULL THEN seats ELSE 0 END) adds booked seats only for rows lacking attendance. It gives three in base. The zero in ELSE means “this row contributes nothing to the unknown-seat subtotal,” not “attendance is zero.” Explain that distinction whenever you use zero inside a conditional aggregate.

2. Let a subquery supply the current comparison

To find bookings larger than the overall mean size:

SELECT reg_id,seats FROM registrations
WHERE seats>(SELECT AVG(seats) FROM registrations)
ORDER BY seats DESC,reg_id;

The inner scalar aggregate supplies one value, 1.4 in base. The outer query compares each booking with it and returns the four two-seat bookings. A hard-coded seats>1.4 happens to agree here but stops representing the intended rule when the fixture changes. Saved analysis should encode the definition, not the last answer.

The inner query is uncorrelated: it does not refer to a particular outer row. An EXISTS query can be correlated:

SELECT i.ingest_id,i.reg_id,i.session_id FROM intake AS i
WHERE NOT EXISTS (
 SELECT 1 FROM sessions AS s WHERE s.session_id=i.session_id
) ORDER BY i.ingest_id;

For each intake claim it asks whether a parent exists. It returns base ingest 3. A NULL claimed parent would also have no matching equality and be flagged. SELECT 1 is not a count: EXISTS only needs a row to exist.

Avoid assuming NOT IN (subquery) is equivalent when that subquery may contain NULL. A comparison against a list containing unknown can itself be unknown, excluding rows you expected to keep. Use the explicit correlated existence test for this relationship question, with an understood key/missingness policy.

STEP 3 OF 6

Original explanation and worked demonstration

3. A CTE is a named intermediate result

A common-table expression begins with WITH name AS (...). It helps you give one stage a name and inspect its grain:

WITH booked AS (
 SELECT session_id,COUNT(*) AS booking_rows,SUM(seats) AS booked_seats,
        SUM(CASE WHEN attended IS NULL THEN seats ELSE 0 END) AS unknown_seats,
        SUM(CASE WHEN attended IS NOT NULL THEN seats ELSE 0 END) AS known_seats,
        SUM(attended) AS recorded_attended_seats
 FROM registrations GROUP BY session_id
)
SELECT s.session_id,s.status,s.capacity,
       COALESCE(b.booking_rows,0) AS booking_rows,
       COALESCE(b.booked_seats,0) AS booked_seats,
       COALESCE(b.unknown_seats,0) AS unknown_seats,
       COALESCE(b.known_seats,0) AS known_seats,
       b.recorded_attended_seats
FROM sessions AS s LEFT JOIN booked AS b ON b.session_id=s.session_id
ORDER BY s.session_id;

Stage one starts with ten bookings and produces four session summaries. Stage two starts with six sessions and matches at most one summary per session, producing six rows. Session 101 now has capacity six once, booked seats four, known seats three and unknown seats one. Session 106 has capacity three, zero bookings and NULL recorded attendance sum.

A CTE is not necessarily a saved table, a materialized cache or a speed improvement. The engine may implement it in different ways. Its value here is a visible reasoning boundary. If you cannot state its grain and key, giving it a name has not solved the problem.

4. COALESCE belongs to a stated reporting rule

When no registration summary matches, there truly are zero booking rows in this fixture for that session. Displaying zero booking rows and zero booked seats is defensible. For recorded attendance, the teaching query deliberately preserves NULL from SUM when no value contributes. A later project view will display an additive recorded lower-bound count as zero but retain known/unknown counts and unavailable rates. Those are explicit conventions with different labels, not contradictory observations.

To diagnose an unexpected result, run the CTE body alone. Count its rows and distinct session IDs; reconcile its booked seats to fourteen; then inspect the joined output. Do not patch an unexplained difference with DISTINCT. Two sessions with capacity four must both contribute to total capacity; two bookings with fee six CAD must both contribute to a fee control.

5. Readability is testability

Use short, meaningful aliases; qualify fields that appear in more than one table; choose output labels with units. Put each major stage on its own lines and save the query. Annotate population changes: a WHERE in the CTE changes what each summary covers. A WHERE on a nullable right-side column after a LEFT JOIN can remove unmatched parents, effectively undoing your “all sessions” intention.

For example, filtering b.booked_seats>0 after the LEFT JOIN excludes 104 and 106. That is fine only if the question is now “sessions with bookings.” It is not a harmless cosmetic filter. The result's row count is an analytical assertion worth testing.

STEP 4 OF 6

Try it yourself

Practice and checkpoint

Complete G6 and I6. The independent mean is also 1.4; do not regard that repeated number as a reason to hard-code it. The changed fixture's mean is 4/3, and a future fixture may differ again. C6 asks for stage-by-stage grain and an equal-value counterexample.

Add session-report.sql and a stage-check note to your cumulative project. Include the orphan query in the quality log. Proceed when you can explain why the final result has exactly one row per supplied session and why that property is stronger evidence than a plausible grand total alone.

Unit 6: CASE, subqueries and CTEs

G6. Classify each base booking as unknown, none recorded, partial or all recorded. Explain CASE branch order. Use a scalar subquery to select bookings above the mean size, not a hard-coded threshold. Build a CTE at session grain, then LEFT JOIN to all sessions, showing booking/known/unknown seat counts and recorded attendance. Identify intake orphan rows with NOT EXISTS. Explain why raw joining cannot safely sum session capacity.

I6. Repeat classification, above-mean selection and the all-session CTE for independent. Count result rows and reconcile booked seats. Explain how the cancellation row differs from an open session with zero bookings. Describe a query using NOT IN that would be unreliable if its subquery could return NULL; show the safe NOT EXISTS formulation.

C6. State the grain and expected maximum number of rows at each CTE/join stage. Would introducing DISTINCT on fee amounts fix a fan-out? Give a changed-value counterexample.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Open-response practice: keep your attempt, then compare the explained answer and rubric. There is no automatic grading or submission to a teacher; review marks are not grades.

STEP 5 OF 6

Worked answer & self-check

Explained key — compare after keeping your attempt

Explained key — Units 6–8 and delayed transfer

The retained Unit 5 key is ../../sql-join-unit/SOLUTIONS.md from this answers directory. Do not apply workshop fixture names to the shop runner.

G6 / I6 / C6: stage contracts

G6 classifications: unknown 1003,1007; none recorded 1002,1009; partial 1004; all recorded 1001,1005,1006,1008,1010. Unknown comes first so ELSE does not mislabel missing values. The constrained trusted source justifies ELSE as all recorded; raw intake would require an invalid category first. Base mean booking size is 1.4, so above-mean IDs are 1001,1004,1005,1007. u06_above_mean encodes the mean calculation rather than memorizing 1.4.

The u06_session_report columns are session_id, status, capacity, booking_rows, booked_seats, unknown_seats, known_seats, recorded_attended_seats:

101 open       6 3 4 1 3 2
102 open       4 2 4 0 4 3
103 open       5 2 3 2 1 1
104 cancelled  0 0 0 0 0 NULL
105 open       4 3 3 0 3 2
106 open       3 0 0 0 0 NULL

Ten source bookings → four grouped session rows → six final rows. The CTE key is session_id; the final key is also session_id. Missing session summaries do not imply measured zero attendance, hence the literal SUM is NULL in this view. Orphan intake result is (3,9002,999); NOT EXISTS tests the absence of a parent match.

I6 classifications: 2001 all recorded; 2002 unknown; 2003 none recorded; 2004 and 2005 all recorded. No partial category occurs. Mean size is 1.4; above-mean IDs 2003,2004. Report rows:

201 open       3 2 2 1 1 1
202 open       2 1 2 0 2 0
203 open       4 2 3 0 3 3
204 cancelled  0 0 0 0 0 NULL

Five bookings → three grouped rows → four final session rows; booked seats reconcile to seven. Orphan is (13,9102,999). Cancellation is a supplied status; an open session with no bookings still contributes to the open-capacity denominator. A zero capacity does not by itself establish cancellation.

For NOT IN, consider SELECT 999 WHERE 999 NOT IN (101,NULL);: the comparison is unknown, so it returns no row. A relationship NOT EXISTS with s.session_id=i.session_id correctly flags 999 as having no parent in this fixture. Do not add NULL silently to an identity set and assume ordinary set subtraction.

C6: name stage grain and row-count limits, not merely the query keywords. DISTINCT fee values is not an identity repair: two valid 250-cent bookings should contribute 500 cents, but SUM(DISTINCT fee_cents) keeps 250 once. The same logic applies to two capacity-four sessions.

Saved model queries and expected fixture tables — static reference, not execution

-- Original model query; attempt workbook task before reading.
SELECT reg_id,seats FROM registrations
WHERE seats>(SELECT AVG(seats) FROM registrations) ORDER BY seats DESC,reg_id;
sql-applied-course / base / u06_above_mean — frozen expected output, not executed in this browser
reg_idseats
10012
10042
10052
10072
sql-applied-course / independent / u06_above_mean — frozen expected output, not executed in this browser
reg_idseats
20032
20042
sql-applied-course / changed / u06_above_mean — frozen expected output, not executed in this browser
reg_idseats
30032
sql-applied-course / empty / u06_above_mean — frozen expected output, not executed in this browser
reg_idseats
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT reg_id,CASE WHEN attended IS NULL THEN 'unknown'
 WHEN attended=0 THEN 'none recorded' WHEN attended<seats THEN 'partial'
 ELSE 'all recorded' END AS attendance_band
FROM registrations ORDER BY reg_id;
sql-applied-course / base / u06_attendance_bands — frozen expected output, not executed in this browser
reg_idattendance_band
1001all recorded
1002none recorded
1003unknown
1004partial
1005all recorded
1006all recorded
1007unknown
1008all recorded
1009none recorded
1010all recorded
sql-applied-course / independent / u06_attendance_bands — frozen expected output, not executed in this browser
reg_idattendance_band
2001all recorded
2002unknown
2003none recorded
2004all recorded
2005all recorded
sql-applied-course / changed / u06_attendance_bands — frozen expected output, not executed in this browser
reg_idattendance_band
3001all recorded
3002none recorded
3003unknown
sql-applied-course / empty / u06_attendance_bands — frozen expected output, not executed in this browser
reg_idattendance_band
No rows returned.
-- Original model query; attempt workbook task before reading.
SELECT i.ingest_id,i.reg_id,i.session_id FROM intake AS i
WHERE NOT EXISTS (SELECT 1 FROM sessions AS s WHERE s.session_id=i.session_id)
ORDER BY i.ingest_id;
sql-applied-course / base / u06_orphans — frozen expected output, not executed in this browser
ingest_idreg_idsession_id
39002999
sql-applied-course / independent / u06_orphans — frozen expected output, not executed in this browser
ingest_idreg_idsession_id
139102999
sql-applied-course / changed / u06_orphans — frozen expected output, not executed in this browser
ingest_idreg_idsession_id
No rows returned.
sql-applied-course / empty / u06_orphans — frozen expected output, not executed in this browser
ingest_idreg_idsession_id
No rows returned.
-- Original model query; attempt workbook task before reading.
WITH booked AS (
 SELECT session_id,COUNT(*) AS booking_rows,SUM(seats) AS booked_seats,
 SUM(CASE WHEN attended IS NULL THEN seats ELSE 0 END) AS unknown_seats,
 SUM(CASE WHEN attended IS NOT NULL THEN seats ELSE 0 END) AS known_seats,
 SUM(attended) AS recorded_attended_seats
 FROM registrations GROUP BY session_id
)
SELECT s.session_id,s.status,s.capacity,COALESCE(b.booking_rows,0) AS booking_rows,
 COALESCE(b.booked_seats,0) AS booked_seats,COALESCE(b.unknown_seats,0) AS unknown_seats,
 COALESCE(b.known_seats,0) AS known_seats,b.recorded_attended_seats
FROM sessions AS s LEFT JOIN booked AS b ON b.session_id=s.session_id
ORDER BY s.session_id;
sql-applied-course / base / u06_session_report — frozen expected output, not executed in this browser
session_idstatuscapacitybooking_rowsbooked_seatsunknown_seatsknown_seatsrecorded_attended_seats
101open634132
102open424043
103open523211
104cancelled00000NULL
105open433032
106open30000NULL
sql-applied-course / independent / u06_session_report — frozen expected output, not executed in this browser
session_idstatuscapacitybooking_rowsbooked_seatsunknown_seatsknown_seatsrecorded_attended_seats
201open322111
202open212020
203open423033
204cancelled00000NULL
sql-applied-course / changed / u06_session_report — frozen expected output, not executed in this browser
session_idstatuscapacitybooking_rowsbooked_seatsunknown_seatsknown_seatsrecorded_attended_seats
301open422021
302open21220NULL
303open30000NULL
sql-applied-course / empty / u06_session_report — frozen expected output, not executed in this browser
session_idstatuscapacitybooking_rowsbooked_seatsunknown_seatsknown_seatsrecorded_attended_seats
No rows returned.

Compare your answer

  • Correct branch meanings; generic comparison; stage grains and unique keys; all parents retained
  • Raw fan-out hidden by DISTINCT; CASE mislabels invalid source; NOT IN NULL trap ignored
  • 3 — demonstrated in this attempt: correct result and defensible reasoning, with requested evidence and transfer test.
  • 2 — partly demonstrated: central method works but a definition, control, edge case or reproduction detail is missing; revise.
  • 1 — not yet demonstrated: an important grain, missingness, denominator or execution error remains, even if one answer happens to match.
  • 0 — no assessable evidence: task absent or only a copied answer with no reasoning/attempt trail.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • U6: compose CASE/subquery/CTE analyses with inspectable stage contracts.

Add session-report.sql and a stage-check note to your cumulative project. Include the orphan query in the quality log. Proceed when you can explain why the final result has exactly one row per supplied session and why that property is stronger evidence than a plausible grand total alone.

Next lesson: Unit 7 — Report what is established, bounded and unknown →

LESSON 7 OF 8 · PLANNED 300 MINUTES

Unit 7 — Report what is established, bounded and unknown

STEP 1 OF 6

Your objective

communicate an analysis with explicit denominators, missingness bounds, limitations and a proportionate next step.

STEP 2 OF 6

The idea

Unit 7 — Report what is established, bounded and unknown

Outcome U7: communicate an analysis with explicit denominators, missingness bounds, limitations and a proportionate next step. Suggested work: five hours with writing/revision, unpiloted. This applies the retained statistics prerequisite; it is not a replacement statistics course.

1. One dataset can support several honest percentages

Base has fourteen booked seats. Attendance is known for eleven of those seats, with eight recorded as attended. Three seats belong to bookings whose attendance count is unknown. Therefore:

  • Known-only attendance: 8/11 ≈ 72.73%. This describes the recorded subset.
  • All-booked lower bound: 8/14 ≈ 57.14%, if none of the unknown booked seats attended.
  • All-booked upper bound: (8+3)/14 ≈ 78.57%, if every unknown booked seat attended.

The bounds use the schema rule that attendance cannot exceed booked seats. They assume the supplied known counts and booking-seat counts are correct and cover the intended records. They do not account for unrecorded walk-ins, wrong entries, missing bookings or attendance outside this data contract. Those are separate data-quality limitations.

Attendance evidence bounds

Complete text alternative: fourteen booked seats are partitioned into eleven seats with recorded attendance and three seats with attendance unknown. Of the eleven known seats, eight attended and three did not. Adding zero through three attended seats from the unknown group gives total attendance from eight through eleven, hence 8/14 to 11/14. The known-only ratio 8/11 is labelled separately and is not the midpoint of the bounds.

2. These are not confidence intervals

The lower and upper figures are logical bounds under stated missingness and count assumptions. They are not probabilities, sampling confidence intervals or predictions. We have not randomly sampled a population, fitted a model or justified a statistical uncertainty calculation.

Likewise, 72.73% is not automatically an unbiased estimate of the full attendance rate. Attendance may be missing for systematic reasons; the fixture does not tell us. The correct response is to label the recorded subset and show the sensitivity to unknown counts, not invent “missing at random” to obtain a tidier sentence.

Rounding is for display only. Calculate with full counts and round the percentage to two decimals at the end. If a decision threshold falls near a displayed value, inspect the original fraction rather than comparing rounded strings. In a small teaching dataset, two decimals aid answer checking; they should not be mistaken for precise knowledge of a real-world process.

STEP 3 OF 6

Original explanation and worked demonstration

3. Booking utilization is a different measure

The five open sessions have listed capacities 6+4+5+4+3=22. Fourteen seats are booked for those sessions, so the booking-to-capacity ratio is 14/22≈63.64%. Session 106 contributes capacity three and zero bookings. Cancelled session 104 is excluded by the open-session population rule, not merely because it happens to have zero capacity.

This is not attendance utilization. Booked seats can fail to attend, and some attendance values are missing. It is not a unique-person reach rate or satisfaction score. It is also not the unweighted mean of session booking percentages: sessions have unequal capacity. Keep the noun attached to the percentage.

The u07_capacity query separately aggregates open capacity at session grain and admitted booking seats for open sessions. Its CROSS JOIN combines two single-row aggregates, so it returns one row without multiplying raw records. This limited use of CROSS JOIN is safe because the row-count contracts are explicit; arbitrary cross joins can multiply rows dramatically.

4. Separate observation, interpretation and action

A useful note has three layers. Observation: “The fixture records fourteen booked seats against twenty-two open-session places.” Interpretation: “Some listed capacity is not represented by bookings; attendance completeness is uneven.” Action: “Check the missing attendance entries and the no-booking session record before using this snapshot to plan another round.”

An overclaim would be: “Design workshops failed because people dislike them; cancel them.” Topic, site, timing, capacity and missingness differ; the data cannot isolate causes. A weak but honest note would list all numbers without an actionable interpretation. The better middle path identifies what can be checked and what would change the recommendation.

The follow-up should be bounded. In this fictional case, ask the source custodian role to confirm whether missing attendance values and no-booking records are complete. Do not send messages or upload files as part of the course. Stop the immediate reconciliation when source corrections are documented and all reported totals agree; planning a real programme would require additional decision evidence beyond this exercise.

5. All unknown and no observations

Suppose one two-seat booking has unknown attendance. Known-only attendance is unavailable because its denominator is zero. The lower bound is 0/2=0%; upper bound 2/2=100%. That range states how little is established; it does not assign every value equal likelihood.

With no bookings at all, additive booked-seat and recorded lower-bound counts may be displayed as zero under our convention, but the all-booked rate has denominator zero and is unavailable. Both bounds should be NULL, not 0%–100%: there is no booked population to describe. If an open session still has positive capacity, its booking/capacity ratio can be 0% even while attendance rate is unavailable. Different denominators explain this apparent contrast.

STEP 4 OF 6

Try it yourself

Practice and checkpoint

Complete G7 and I7, writing the note before viewing the model. Each note must name the population, at least one numerator/denominator, the unknown component, one unsupported claim and an appropriate next step. C7 distinguishes all-unknown from empty data.

Save uncertainty-note.md and the exact SQL that generated its figures. During revision, highlight any sentence that sounds causal or predictive and ask whether the records support it. You are ready for the project when a reader can understand both what your numbers establish and why they should not be used for a broader claim.

Unit 7: communicating uncertainty

G7. Compute base known-only attendance, lower/upper all-booked-seat bounds, and booked/open-capacity ratio. Write numerator and denominator for each. Explain why the bounds are not a confidence interval and why booked capacity is not attendance. Write a five-sentence coordinator note with a decision, evidence, caveat, follow-up and a stopping condition for the recommendation.

I7. On independent, calculate the same three measures and critique “Attendance is 66.67%, so next month will be the same.” Include missingness, noncausality and scope. Identify a permissible operational follow-up that does not infer causes or send private data.

C7. A new fixture contains one two-seat booking with unknown attendance and no known values. State known-only rate and all-booked lower/upper bounds. Then state what changes when there are no bookings at all.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Open-response practice: keep your attempt, then compare the explained answer and rubric. There is no automatic grading or submission to a teacher; review marks are not grades.

STEP 5 OF 6

Worked answer & self-check

Explained key — compare after keeping your attempt

G7 / I7 / C7: which percentage?

G7: base known-only attendance 8/11=72.73%; all-booked bounds 8/14=57.14% to 11/14=78.57%; booked/open-capacity 14/22=63.64%. Bounds assume the supplied known counts and seat totals are correct and every unknown booking has attendance from zero through its reserved seats. They are not confidence intervals, causal estimates or a forecast.

A suitable five-sentence note: “Check the missing attendance entries and the open session with no bookings before using this snapshot for next-round planning. The supplied records show fourteen booked seats against twenty-two open-session places, or 63.64%. Attendance is recorded for eleven booked seats, of which eight attended; under the stated count rules, attendance across all fourteen booked seats is between 57.14% and 78.57%. These records cannot establish unique people reached, reasons for nonattendance or future demand. Reconcile any source corrections and rerun the saved queries before revising the planning note.” This is an original model, not a required script.

I7: known-only 4/6=66.67%; all-booked bounds 4/7=57.14% to 5/7=71.43%; booked/open-capacity 7/9=77.78%. “Attendance is 66.67%” omits that one booked seat is unknown. “Next month will be the same” adds an unsupported forecast. The appropriate fictional follow-up is checking booking 2002's attendance source and confirming the snapshot's completeness; it is not cancelling a topic, inferring motives or sharing private data.

C7: one two-seat unknown booking gives known-only rate NULL, lower 0%, upper 100%. Empty bookings give known-only/lower/upper rates NULL. Additive counts may be displayed zero by convention; a rate requires a defined nonzero denominator. An open session with capacity but no bookings can have booking/capacity 0% without having an observed attendance rate.

Saved model queries and expected fixture tables — static reference, not execution

-- Original model query; attempt workbook task before reading.
WITH totals AS (
 SELECT COUNT(*) AS booking_rows,COALESCE(SUM(seats),0) AS booked_seats,
 COALESCE(SUM(attended),0) AS recorded_attended_seats,
 COALESCE(SUM(CASE WHEN attended IS NULL THEN seats ELSE 0 END),0) AS unknown_seats,
 COALESCE(SUM(CASE WHEN attended IS NOT NULL THEN seats ELSE 0 END),0) AS known_seats
 FROM registrations
)
SELECT booking_rows,booked_seats,recorded_attended_seats,unknown_seats,known_seats,
 ROUND(100.0*recorded_attended_seats/NULLIF(known_seats,0),2) AS known_attendance_pct,
 ROUND(100.0*recorded_attended_seats/NULLIF(booked_seats,0),2) AS lower_pct,
 ROUND(100.0*(recorded_attended_seats+unknown_seats)/NULLIF(booked_seats,0),2) AS upper_pct
FROM totals;
sql-applied-course / base / u07_bounds — frozen expected output, not executed in this browser
booking_rowsbooked_seatsrecorded_attended_seatsunknown_seatsknown_seatsknown_attendance_pctlower_pctupper_pct
1014831172.7357.1478.57
sql-applied-course / independent / u07_bounds — frozen expected output, not executed in this browser
booking_rowsbooked_seatsrecorded_attended_seatsunknown_seatsknown_seatsknown_attendance_pctlower_pctupper_pct
5741666.6757.1471.43
sql-applied-course / changed / u07_bounds — frozen expected output, not executed in this browser
booking_rowsbooked_seatsrecorded_attended_seatsunknown_seatsknown_seatsknown_attendance_pctlower_pctupper_pct
34122502575
sql-applied-course / empty / u07_bounds — frozen expected output, not executed in this browser
booking_rowsbooked_seatsrecorded_attended_seatsunknown_seatsknown_seatsknown_attendance_pctlower_pctupper_pct
00000NULLNULLNULL
-- Original model query; attempt workbook task before reading.
WITH capacity AS (
 SELECT COALESCE(SUM(capacity),0) AS open_capacity FROM sessions WHERE status='open'
), booked AS (
 SELECT COALESCE(SUM(r.seats),0) AS booked_open_seats FROM registrations AS r
 WHERE EXISTS (SELECT 1 FROM sessions AS s WHERE s.session_id=r.session_id AND s.status='open')
)
SELECT open_capacity,booked_open_seats,
 ROUND(100.0*booked_open_seats/NULLIF(open_capacity,0),2) AS booking_capacity_pct
FROM capacity CROSS JOIN booked;
sql-applied-course / base / u07_capacity — frozen expected output, not executed in this browser
open_capacitybooked_open_seatsbooking_capacity_pct
221463.64
sql-applied-course / independent / u07_capacity — frozen expected output, not executed in this browser
open_capacitybooked_open_seatsbooking_capacity_pct
9777.78
sql-applied-course / changed / u07_capacity — frozen expected output, not executed in this browser
open_capacitybooked_open_seatsbooking_capacity_pct
9444.44
sql-applied-course / empty / u07_capacity — frozen expected output, not executed in this browser
open_capacitybooked_open_seatsbooking_capacity_pct
00NULL

Compare your answer

  • Correctly named ratios/bounds, assumptions, limits and proportionate next step
  • Causal/predictive certainty; logical bounds called confidence interval
  • 3 — demonstrated in this attempt: correct result and defensible reasoning, with requested evidence and transfer test.
  • 2 — partly demonstrated: central method works but a definition, control, edge case or reproduction detail is missing; revise.
  • 1 — not yet demonstrated: an important grain, missingness, denominator or execution error remains, even if one answer happens to match.
  • 0 — no assessable evidence: task absent or only a copied answer with no reasoning/attempt trail.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • U7: communicate measures, logical bounds and limitations without causal overclaim.

Save uncertainty-note.md and the exact SQL that generated its figures. During revision, highlight any sentence that sounds causal or predictive and ask whether the records support it. You are ready for the project when a reader can understand both what your numbers establish and why they should not be used for a broader claim.

Next lesson: Unit 8 — Deliver an analysis someone can rerun and challenge →

LESSON 8 OF 8 · PLANNED 600 MINUTES

Unit 8 — Deliver an analysis someone can rerun and challenge

STEP 1 OF 6

Your objective

assemble source contracts, saved queries, controls, interpretation and changed-data tests into a reproducible local handoff.

STEP 2 OF 6

The idea

Unit 8 — Deliver an analysis someone can rerun and challenge

Outcome U8: assemble source contracts, saved queries, controls, interpretation and changed-data tests into a reproducible local handoff. Suggested work: ten hours including independent project, later-day transfer and revision; unpiloted. This is a self-study project, not externally graded certification.

1. Reproducibility is more than a screenshot

A screenshot can show a number, but it may not reveal which fixture, filter, query version or runtime produced it. A reproducible handoff lets another reader reconstruct the result from the stated source without guessing. It also exposes limitations rather than burying them in undocumented steps.

Our package uses a fresh in-memory database for each run. schema.sql defines the tables; one fixture supplies records; one saved SELECT describes the output; the runner prints the fixture and SQLite version with the result. Nothing persists in a database between runs. If you edit a query, save it in your learning folder; if you need a result file, redirect output deliberately. Do not assume the runner saved either for you.

Keep original source fixtures unchanged. Record their supplied manifest hashes or calculate your own file hash using an existing tool. A hash detects byte differences; it does not prove the source is accurate, authorized or complete. The provenance note must still say the data are synthetic and explain the analytical population.

STEP 3 OF 6

Original explanation and worked demonstration

2. The worked base analysis has a spine

Begin with controls: six sessions, ten bookings, fourteen booked seats, 7,800 fee cents and six raw intake claims. Raw intake is outside the trusted booking population. Reconcile sums from the grouped output to fourteen seats and eight recorded attended seats. A change in source count should be explained, not patched by changing expected answers until a test passes.

Next, build one row per session using the CTE pattern. The base rows show:

  • 101: capacity 6, booked 4, attendance between 2 and 3 of those booked seats.
  • 102: capacity 4, booked 4, recorded attendance 3, no unknown attendance seats.
  • 103: capacity 5, booked 3, attendance between 1 and 3, because two booked seats lack attendance.
  • 104: cancelled with capacity 0, no bookings; booking/capacity and attendance rates unavailable.
  • 105: capacity 4, booked 3, recorded attendance 2, no unknown seats.
  • 106: open capacity 3, no bookings; booking/capacity 0%, attendance rate unavailable.

The project view explicitly displays zero additive recorded attended seats when none contributes; it does not imply observed zero attendance. Known seats, unknown seats and denominator-aware rates preserve the difference. Compare this convention with the more literal SUM output retained in Unit 6.

Finally, write a bounded note: booking/capacity is 14/22=63.64%; known-only attendance is 8/11=72.73%; all-booked attendance lies from 8/14 to 11/14 under the stated count assumptions. Check missing attendance for sessions 101 and 103 and the no-booking record for 106 before using the snapshot for planning. Do not infer causes or future demand.

3. Preserve a deliberately wrong query as diagnostic evidence

Run a raw session–registration LEFT JOIN and sum capacity. Session 101 appears three times, 102 twice, 103 twice, 105 three times; childless 104 and 106 each contribute one output row. The sum is 18+8+10+0+12+3=51, not 22. This is a fan-out diagnostic, not a plausible capacity estimate.

SUM(DISTINCT capacity) gives 6+4+5+0+3=18; it incorrectly merges the two separate capacity-four sessions. A correct count beside this sum would not repair the sum. The source-grain open-capacity query gives 22, and the one-row-per-session report preserves that grain. Save the failed query, observed result and explanation in your correction log. Failure evidence is useful when it demonstrates why the final method is needed.

4. A reproducibility test should challenge a definition

Test the equal-fee bookings: source fee sum is 7,800 cents, while DISTINCT fees total only 1,800. Equal amounts are not duplicate identities. Test the unknown-attendance bookings: their seats remain in the all-booked denominator but not the known-only denominator. Test empty input: counts can be zero, rates unavailable. Test deterministic ordering by comparing full ordered outputs, not only their sums.

For delayed transfer, use changed rather than editing the base in place. The query logic should still describe the question without hard-coded IDs or thresholds. A no-booking session and an all-unknown session test different branches. If a result surprises you, inspect intermediate row grains and source controls before adding a cosmetic fix.

A small diagnostic transaction is included in the automated suite: change a disposable attendance value, then roll back and verify the original NULL remains. This illustrates reversibility in a local test. It does not deliver the semester's full correction-workflow and concurrency teaching, and the learner runner intentionally permits SELECT only. Do not execute UPDATE statements on real systems to imitate the demonstration.

STEP 4 OF 6

Try it yourself

5. Handoff and self-review

Follow PROJECT.md for the independent deliverables and the rubric. A complete local attempt includes six artifacts: source/question note, SQL files, observed outputs, control/test log, decision note and reproduction instructions. An executable project requires actual runtime evidence; paper-only reasoning should be labelled as such and can be completed later on a suitable local device.

Ask a reviewer of your own choosing to inspect the work only if you decide to share it; this course neither sends files nor secures external reviewers. Self-check against the explained key after retaining your first attempt. The purpose is diagnosis and revision, not awarding a credential. A numerical self-score cannot substitute for independent competence evidence.

On a later day complete D8 without the model solutions. Keep the changed-data result and a revision memo. This is the end of the bounded applied sequence, not completion of the retained 108-hour semester profile. Scope reconciliation records what remains before that broader course could be claimed.

Unit 8: cumulative project and delayed transfer

G8. Follow the worked project architecture in Unit 8 using base, but produce your own saved queries and note before reading PROJECT-KEY.md. Keep question/grain, quality log, grouped summary, JOIN reconciliation and uncertainty note from earlier units. Add source controls and an exact reproduction command.

I8. Independent project. Use independent only. Deliver the six artifacts in PROJECT.md. The coordinator asks: “Which session records need checking before next-round planning, how full are open sessions by bookings, and what does attendance currently establish?” Do not answer unique reach, profitability or causality. Include a deliberately wrong raw-join capacity sum, diagnose it at entity level, and repair it. Show exact fees only as a units/control exercise. Use the rubric, retain first attempt, then write a revision log after checking the key.

D8. Delayed transfer (on a later day, first attempt without solutions). Use changed. Predict all source totals, all-session report, booking/capacity rate and attendance bounds before execution. Session 303 has no booking; 302 has only unknown attendance; two distinct bookings have equal fee amounts. Explain how each defeats a plausible shortcut. Then run the empty fixture. Produce a three-paragraph revision memo: what changed, which query logic should stay unchanged, what the data still cannot establish.

C8. Reproduction challenge. Close your notes, open a fresh terminal in this package, and run a saved query against the named fixture. Verify runtime label and reconcile the result from the source rows. If you cannot execute on your device, label the work “reasoned, execution pending”; do not claim executable project completion.

Reusable response sheet

Task ID / fixture / question / initial prediction / source counts / SQL filename / runtime / output file or hand trace / comparison / limitation / correction / later-day reattempt date.

Use as much space as reasoning requires. No name, email or other identifying information is needed.

Independent cumulative project

Fixture: independent. Audience: fictional workshop coordinator. Question: Which session records need checking before next-round planning, how full are open sessions by bookings, and what does the attendance evidence establish?

Use only supplied synthetic data. Do not create accounts, upload records, contact people or connect to a real database. Write your own queries before opening the key. No personal identifiers are needed in your files.

Deliver six local artifacts

  • 1. source-and-question.md: question/populations; source fixture and manifest/version; table grains/keys; admitted versus raw records; date and missingness conventions; unit choices; three unanswerable questions. Preserve the retained prerequisite boundary: this is SQL application, not new statistics, Python or accounting certification.
  • 2. queries/: saved SQL for source controls, selected records, grouped summaries, an all-session CTE report, raw intake checks, attendance bounds and open-capacity ratio. Include a deliberately wrong raw-join capacity sum in a clearly marked diagnostic file and explain its repair. Every multirow deliverable needs deterministic order.
  • 3. results/: actual local runner output with fixture and SQLite version. If your runtime differs, preserve the unvalidated-version label and compare carefully. A paper trace belongs in a separately labelled reasoning section, not in executed-results evidence.
  • 4. checks-and-corrections.md: hand/source controls; grouped reconciliation; foreign-key/orphan and duplicate-identity reasoning; no-match, unknown, zero, equal-value and empty-case tests; initial error and justified correction. State which checks you actually ran and which you reasoned through. Explain the cents/display rounding policy.
  • 5. coordinator-note.md: approximately 200–350 words is a helpful target, not a grading trick. Answer the decision question with correct nouns and denominators, missingness limits, one bounded next step and a stopping condition. Do not infer unique people, profitability, motivation or causal effects.
  • 6. REPRODUCE.md: exact fixture/query commands, required local runtime, expected key controls, source/analysis filenames and a minimal simulated access/retention plan. Distinguish reading versus execution and self-review versus external marking. Anyone reproducing should start with a fresh in-memory database, not your prior session state.

Required tests and transfer

  • Explain why two valid equal-fee bookings must remain two entities.
  • Show why session capacity cannot be summed on raw joined booking rows.
  • Distinguish zero attendance, unknown attendance and no booking row.
  • Keep a zero denominator unavailable; don't show a fake 0% attendance result.
  • Predict changed-data totals before rerunning your generic queries on changed.
  • Return on a later day for D8 without the answer key, then preserve your revision.

Access/retention simulation

For this synthetic package, a learner may read the whole fixture locally. For the fictional real-world analogy, propose a role that admits source corrections and a role that reads only aggregated planning output; explain why unnecessary booking references should not be in the coordinator note. State when raw evidence would be reviewed for retention under an agreed policy and who owns that decision. Do not invent a legal retention period or claim SQLite here enforces role-based access. No actual permission or deletion change is part of this task.

Review sequence

First use the outcome map to check coverage; then use RUBRIC.md; finally compare to answers/PROJECT-KEY.md and record changes. A complete self-study submission is a package with visible reasoning and actual local evidence where execution is claimed. It is not a secured independently assessed offering, semester completion or a qualification.

Fictional exercise · prewritten feedback, no live AI grading.

Write your answer on paper or in your own notes, then compare the options and worked answer.

Open-response practice: keep your attempt, then compare the explained answer and rubric. There is no automatic grading or submission to a teacher; review marks are not grades.

STEP 5 OF 6

Worked answer & self-check

Explained key — compare after keeping your attempt

G8 / I8: project

Use PROJECT-KEY.md for exact control totals, diagnostic wrong joins, session-level results and acceptable decisions. Complete means reasoning plus reproducible evidence, not a copied screenshot. u08_project_session_report uses explicit zero additive lower-bound counts and nullable rates; it must be explained, not mistaken for complete attendance observations.

D8: delayed changed-data transfer

Source: 3 sessions,3 bookings,3 booking references,4 booked seats,1 recorded attended seat,2 known booked seats,2 unknown booked seats,1,000 fee cents,0 intake rows. All sessions are open with capacity 4+2+3=9.

Booking/capacity 4/9=44.44%.
Known-only attendance 1/2=50%.
All-booked attendance bounds 1/4=25% through 3/4=75%.
Booking mean size 4/3≈1.3333; above-mean booking 3003 (two seats).
Correct fee total 1,000 cents; DISTINCT fee shortcut 750 cents because it merges the two separate 250-cent bookings. Mean fee CAD 3.33 after display rounding.

Project session report:

D8: delayed changed-data transfer — table 1
SessionCapacityBookingsBooked seatsKnown seatsUnknown seatsRecorded attendedBooking/capacityLower attendanceUpper attendance
30142220150%50%50%
302212020100%0%100%
3033000000%NULLNULL

For 302 the displayed recorded lower-bound count zero is not observed zero attendance: all attendance is unknown. For 303 there are no bookings at all, hence no attendance population. u06_session_report, which preserves literal SUM, shows NULL recorded attendance for both; the additional known/unknown/booked fields distinguish them.

The raw LEFT JOIN has four rows and sums capacity to 13 (4+4+2+3) instead of nine. SUM(DISTINCT capacity) happens to give nine because all three capacities differ. This apparent success is broken by base, where capacities repeat across distinct sessions. A counterexample tests a method beyond one conveniently matching result.

With empty, inventory is (0,0,NULL); the explicit source-control view is (0,0,0,0,0); all-session reports have no rows; bounds view displays zero counts and NULL rates; capacity view gives zero capacity, zero bookings and NULL rate. Scalar SUM/AVG remain NULL unless the query explicitly applies a documented zero-total convention. Empty output is not a failed execution if that is the correct result.

An acceptable revision memo identifies changed records/counts, retains generic grouping/existence/NULL-safe logic and refuses causal or predictive claims. No delayed-learning success is asserted until a learner actually returns on a later day and attempts it.

Independent project: model evidence and explained decisions

This is one acceptable solution architecture, not an external grading decision. Compare after retaining your attempt. Equivalent SQL and appropriately cautious decisions are welcome.

Source and controls

The independent fixture has 4 sessions, 5 booking records, 4 booking references, 7 booked seats, 1,500 fee cents and 6 raw intake claims. Three open sessions have total capacity 9; cancelled 204 has capacity 0. Four booking rows have attendance recorded, covering six seats; recorded attended seats total four. Booking 2002 represents the one unknown seat.

u08_controls returns (4,5,7,1500,6) in columns sessions, booking_rows, booked_seats, fee_cents, raw_intake_rows. u01_inventory returns (5,4,7). Distinct references are not unique participants. The source contains no person-level evidence to answer unique reach.

All-session answer

All-session answer — table 1
SessionStatusCapacityBookingsBooked seatsKnown seatsUnknown seatsRecorded attendedBooking/capacityLower attendanceUpper attendance
201open32211166.67%50%100%
202open212200100%0%0%
203open42330375%100%100%
204cancelled000000NULLNULLNULL

Counts reconcile to five bookings, seven seats, six known seats, one unknown seat and four recorded attendees counted as seats. For 204, displayed zero additive counts do not create an attendance population. Session 202 really records zero attended seats for a two-seat booking; that is different from 204's absence of bookings and 201's partially unknown attendance.

Wrong join and repair

A raw LEFT JOIN produces six rows: 201 twice, 202 once, 203 twice, 204 once. Summing capacity gives 3+3+2+4+4+0=16, not nine. The extra seven is one repeated 3 and one repeated 4. INNER JOIN removes cancelled 204's zero row, leaving five rows and the same wrong sum 16; a matching wrong sum across join types is not validation.

Here SUM(DISTINCT capacity) happens to be 9, because distinct session capacities are 3,2,4,0. Base defeats the shortcut: two separate sessions have capacity four, so DISTINCT merges legitimate entities. Repair by summing open capacity directly from sessions or by joining a one-row-per-session summary and verifying its unique key. Do not use accidental agreement as proof.

Fee control is 1,500 cents=CAD 15.00, mean per booking CAD 3.00. DISTINCT fee sum is 750 cents, dropping one valid 250-cent and one valid 500-cent contribution. No conclusion about payment or profit follows from this control.

Missingness and comparison

Known-only attendance is 4/6=66.67%. All-booked attendance is bounded by 4/7=57.14% and 5/7=71.43%, conditional on the supplied booked and known-attendance counts being correct. Booking-to-open-capacity is 7/9=77.78%. These are different measures. Bounds are not a statistical confidence interval; the scenario provides neither random sampling nor a predictive model.

Quality log should flag raw duplicate claims 11/12, orphan 13, missing ID 14, zero seats 15 and attendance above seats 16. These raw records remain outside the trusted totals. A future record could fail several rules; error-class totals do not necessarily count distinct bad rows.

Model coordinator note

The next step is to check session 201's missing attendance entry and confirm the completeness of the supplied snapshot before using attendance to plan the next round. Across the three listed open sessions, seven seats are booked against nine places, a booking-to-capacity ratio of 77.78%. Session 202 is fully booked by this measure, while 201 and 203 have booked ratios of 66.67% and 75% respectively; booking is not the same as attendance.

Attendance is recorded for six of the seven booked seats. Four of those six attended, giving a known-only rate of 66.67%. One booked seat in session 201 has no attendance count. Under the supplied count rules, all-booked attendance is therefore between four and five seats, or 57.14%–71.43%. Session 202 records zero attendance for its two booked seats, but the records do not explain why. These small synthetic records cannot establish unique people reached, satisfaction, causal effects, profitability or next month's demand.

Keep the six problematic intake claims separate from the admitted bookings and ask the fictional source-custodian role to resolve their identity, parent and count issues. Preserve the original source and record every justified correction. Rerun the saved queries and reconcile controls after any admitted correction; stop this reconciliation when those corrections and remaining unresolved fields are explicitly documented. A broader programme decision would still require additional evidence beyond this SQL exercise.

Reproduction example

From the package root, with the pinned runtime:

python3 run.py independent --query u08_controls
python3 run.py independent --query u08_project_session_report
python3 run.py independent --query u07_bounds
python3 run.py independent --query u07_capacity
python3 run.py independent --query u03_duplicate_intake
python3 run.py independent --query u03_invalid_intake
python3 run.py independent --query u06_orphans
python3 run.py changed --query u08_project_session_report
python3 run.py empty --query u07_bounds
python3 -m unittest -v

Actual outputs, not these commands alone, establish execution. Add your own query filenames with --file. Use a different folder for your results to avoid altering the authored evidence. A simulated role/access plan is acceptable if it minimizes shared fields and assigns responsibility without claiming an implemented permission system or an invented legal retention period.

Saved model queries and expected fixture tables — static reference, not execution

-- Original model query; attempt workbook task before reading.
SELECT (SELECT COUNT(*) FROM sessions) AS sessions,
 (SELECT COUNT(*) FROM registrations) AS booking_rows,
 (SELECT COALESCE(SUM(seats),0) FROM registrations) AS booked_seats,
 (SELECT COALESCE(SUM(fee_cents),0) FROM registrations) AS fee_cents,
 (SELECT COUNT(*) FROM intake) AS raw_intake_rows;
sql-applied-course / base / u08_controls — frozen expected output, not executed in this browser
sessionsbooking_rowsbooked_seatsfee_centsraw_intake_rows
6101478006
sql-applied-course / independent / u08_controls — frozen expected output, not executed in this browser
sessionsbooking_rowsbooked_seatsfee_centsraw_intake_rows
45715006
sql-applied-course / changed / u08_controls — frozen expected output, not executed in this browser
sessionsbooking_rowsbooked_seatsfee_centsraw_intake_rows
33410000
sql-applied-course / empty / u08_controls — frozen expected output, not executed in this browser
sessionsbooking_rowsbooked_seatsfee_centsraw_intake_rows
00000
-- Original model query; attempt workbook task before reading.
SELECT COUNT(*) AS booking_rows,SUM(fee_cents) AS fee_cents,
 SUM(DISTINCT fee_cents) AS wrong_distinct_fee_cents,
 ROUND(AVG(fee_cents)/100.0,2) AS mean_fee_cad FROM registrations;
sql-applied-course / base / u08_fee_sanity — frozen expected output, not executed in this browser
booking_rowsfee_centswrong_distinct_fee_centsmean_fee_cad
10780018007.8
sql-applied-course / independent / u08_fee_sanity — frozen expected output, not executed in this browser
booking_rowsfee_centswrong_distinct_fee_centsmean_fee_cad
515007503
sql-applied-course / changed / u08_fee_sanity — frozen expected output, not executed in this browser
booking_rowsfee_centswrong_distinct_fee_centsmean_fee_cad
310007503.33
sql-applied-course / empty / u08_fee_sanity — frozen expected output, not executed in this browser
booking_rowsfee_centswrong_distinct_fee_centsmean_fee_cad
0NULLNULLNULL
-- Original model query; attempt workbook task before reading.
WITH b AS (
 SELECT session_id,COUNT(*) AS booking_rows,SUM(seats) AS booked_seats,
 SUM(CASE WHEN attended IS NOT NULL THEN seats ELSE 0 END) AS known_seats,
 SUM(CASE WHEN attended IS NULL THEN seats ELSE 0 END) AS unknown_seats,
 COALESCE(SUM(attended),0) AS recorded_attended_seats
 FROM registrations GROUP BY session_id
)
SELECT s.session_id,s.status,s.capacity,COALESCE(b.booking_rows,0) AS booking_rows,
 COALESCE(b.booked_seats,0) AS booked_seats,COALESCE(b.known_seats,0) AS known_seats,
 COALESCE(b.unknown_seats,0) AS unknown_seats,COALESCE(b.recorded_attended_seats,0) AS recorded_attended_seats,
 ROUND(100.0*COALESCE(b.booked_seats,0)/NULLIF(s.capacity,0),2) AS booking_capacity_pct,
 ROUND(100.0*b.recorded_attended_seats/NULLIF(b.booked_seats,0),2) AS lower_attendance_pct,
 ROUND(100.0*(b.recorded_attended_seats+b.unknown_seats)/NULLIF(b.booked_seats,0),2) AS upper_attendance_pct
FROM sessions AS s LEFT JOIN b ON b.session_id=s.session_id ORDER BY s.session_id;
sql-applied-course / base / u08_project_session_report — frozen expected output, not executed in this browser
session_idstatuscapacitybooking_rowsbooked_seatsknown_seatsunknown_seatsrecorded_attended_seatsbooking_capacity_pctlower_attendance_pctupper_attendance_pct
101open63431266.675075
102open4244031007575
103open5231216033.33100
104cancelled000000NULLNULLNULL
105open4333027566.6766.67
106open3000000NULLNULL
sql-applied-course / independent / u08_project_session_report — frozen expected output, not executed in this browser
session_idstatuscapacitybooking_rowsbooked_seatsknown_seatsunknown_seatsrecorded_attended_seatsbooking_capacity_pctlower_attendance_pctupper_attendance_pct
201open32211166.6750100
202open21220010000
203open42330375100100
204cancelled000000NULLNULLNULL
sql-applied-course / changed / u08_project_session_report — frozen expected output, not executed in this browser
session_idstatuscapacitybooking_rowsbooked_seatsknown_seatsunknown_seatsrecorded_attended_seatsbooking_capacity_pctlower_attendance_pctupper_attendance_pct
301open422201505050
302open2120201000100
303open3000000NULLNULL
sql-applied-course / empty / u08_project_session_report — frozen expected output, not executed in this browser
session_idstatuscapacitybooking_rowsbooked_seatsknown_seatsunknown_seatsrecorded_attended_seatsbooking_capacity_pctlower_attendance_pctupper_attendance_pct
No rows returned.

Compare your answer

  • Six artifacts, real execution evidence when claimed, controls, correction trail and delayed transfer
  • No reproducible source/query; fabricated runtime evidence; private data or unsupported completion claim
  • 3 — demonstrated in this attempt: correct result and defensible reasoning, with requested evidence and transfer test.
  • 2 — partly demonstrated: central method works but a definition, control, edge case or reproduction detail is missing; revise.
  • 1 — not yet demonstrated: an important grain, missingness, denominator or execution error remains, even if one answer happens to match.
  • 0 — no assessable evidence: task absent or only a copied answer with no reasoning/attempt trail.

Give yourself one check for each point your work meets. Revise any missing piece. This is a self-check, not a score sent to a teacher.

STEP 6 OF 6

Recap & next step

  • U8: deliver a reproducible local project with controls and changed-data evidence.

On a later day complete D8 without the model solutions. Keep the changed-data result and a revision memo. This is the end of the bounded applied sequence, not completion of the retained 108-hour semester profile. Scope reconciliation records what remains before that broader course could be claimed.

Revisit the course → · Choose another course →

Sources & learning limits

Examples, exercises and worked answers are original fictional teaching material. Source checks inform the factual explanations; these organisations do not endorse this course.

This independent course is general education, not accreditation, a degree, professional advice or a promise of competence. No institutional affiliation or endorsement is implied. The illustrated setting is fictional.