Applied edition · 44 planned hours · Unpiloted · Human review pending. Self-review is not a credential; the full 108-hour semester remains unfinished. No browser SQL execution.
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
| order_id | customer_id | amount_cad |
|---|---|---|
| 101 | A | 100 |
| 102 | A | 60 |
| 103 | B | 40 |
| 104 | C | 80 |
| item_id | order_id |
|---|---|
| 1 | 101 |
| 2 | 101 |
| 3 | 102 |
| 4 | 103 |
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.
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;| order_id | customer | order amount CAD | item_id |
|---|---|---|---|
| 101 | A | 100 | 1 |
| 101 | A | 100 | 2 |
| 102 | A | 60 | 3 |
| 103 | B | 40 | 4 |
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:
- The question and population: all recorded orders or those with recorded items?
- Each table's grain, primary key and relationship.
- Source counts and a parent-grain control total.
- Predicted join row counts, then actual rows and unmatched IDs.
- Correct aggregation, count/denominator, units and rounding.
- At least one changed-data test, especially equal values or no matches.
- 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.