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;
| booking_rows | booking_refs | booked_seats |
|---|---|---|
| 10 | 8 | 14 |
| booking_rows | booking_refs | booked_seats |
|---|---|---|
| 5 | 4 | 7 |
| booking_rows | booking_refs | booked_seats |
|---|---|---|
| 3 | 3 | 4 |
| booking_rows | booking_refs | booked_seats |
|---|---|---|
| 0 | 0 | NULL |
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 →