# 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](queries/inner_rows.sql), [left_rows.sql](queries/left_rows.sql). Their explicit ORDER BY makes inspection reproducible; SQL does not otherwise promise this display order.

### G3. Totals and cancellation of errors

| Question/method | Result CAD | Explanation |
|---|---:|---|
| All orders, sum directly from orders | 280 | 100+60+40+80 |
| Raw inner joined sum (wrong for either requested order total) | 300 | 100+100+60+40 |
| Raw left joined sum (wrong all-order total) | 380 | 100+100+60+40+80 |
| Orders with at least one item, correct | 200 | 100+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](queries/all_value.sql), [inner_wrong_value.sql](queries/inner_wrong_value.sql), [left_wrong_value.sql](queries/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

| Join | COUNT(*) | COUNT(i.item_id) | COUNT(DISTINCT o.order_id) |
|---|---:|---:|---:|
| Inner | 4 | 4 | 3 |
| Left | 5 | 4 | 4 |

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](queries/join_counts.sql) is the left-join version; replacing LEFT JOIN with INNER JOIN gives the other row.

[per_order_counts.sql](queries/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](queries/all_value.sql) and no join. Item-bearing order value uses [item_value_exists.sql](queries/item_value_exists.sql), or [item_value_distinct_keys.sql](queries/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](queries/all_mean.sql), [item_mean.sql](queries/item_mean.sql), [inner_wrong_mean.sql](queries/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)

| Measure | CAD |
|---|---:|
| Correct all-order total | 380 |
| Correct item-bearing total | 300 |
| Raw inner joined sum | 400 |
| Raw left joined sum | 480 |
| SUM(DISTINCT amount_cad) on the inner join | 200 |

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](queries/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](queries/staging_orphans.sql) returns `(item_id=9, order_id=999)`. That raw item has no matching parent. By contrast, [no_item_orders.sql](queries/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

| Measure | Independent result |
|---|---:|
| All-order total | 200 CAD |
| Item-bearing total | 100 CAD |
| Raw INNER JOIN sum | 150 CAD |
| Raw LEFT JOIN sum | 250 CAD |
| SUM(DISTINCT amount_cad) on inner join | 50 CAD |
| All-order mean | 40 CAD |
| Item-bearing mean | 100/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.
