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

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

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

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

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

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

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