# 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.

## 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.

## 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.

## 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.

## 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.

## 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.

## 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.

## 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.
