Harbor Supply wants one row per order showing gross charges, refunds and net amount. A query that joins every line to every refund can return one row per order after GROUP BY and still report the wrong money. The error happened before the grouping.
Use the checked small fixture from the fixture lesson. Its gross is 200.00 and refunds 25.00. All amounts use one fictional currency unit. For this report, an order with no recorded charges/refunds contributes zero for that absent measure. Stored amounts themselves cannot be null. This is a specific report policy, not a general rule that every missing value means zero.
The required output grain is one row per order_id. That key is unique in
the parent orders table. Keep it explicit while choosing each relationship.
Follow the multiplication before adding an aggregate

The arrows show logical row relationships, not a physical execution plan or timing claim. On the left, each line matches both refunds through the same order. On the right, each child relationship has already become at most one row per order before joining back to the parent.
For order 101, the raw joined inputs contain:
| Line | Line amount | Refund | Refund amount |
|---|---|---|---|
| 11 | 40.00 | 21 | 5.00 |
| 11 | 40.00 | 22 | 15.00 |
| 12 | 60.00 | 21 | 5.00 |
| 12 | 60.00 | 22 | 15.00 |
| 13 | 20.00 | 21 | 5.00 |
| 13 | 20.00 | 22 | 15.00 |
Each line amount appears twice; each refund appears three times. SUM therefore sees gross 240.00 and refunded 60.00, although the independent facts are 120.00 and 20.00. Grouping those six inputs by order ID changes the result's row count; it does not reconstruct the facts that were repeated.
If you joined order 101's three raw fulfilment events as well, each of these six pairs would match three events. The intermediate grain would contain 18 line–refund–event combinations. More GROUP BY columns can describe those combinations but cannot make them legitimate monetary observations.
Make each child answer one question at the required grain
First ask the lines table for a gross total per order. Separately ask refunds for a refund total per order. Each grouped result has at most one row for a given key. Joining those results to orders now preserves the desired grain.
The parenthesized SELECT inside FROM/JOIN is a derived table: a query
result used as that relationship's input. Its alias, such as l, names that
input, not a permanent database table. A grouped query you already know can
therefore establish a row contract before the outer query combines it with
another result. Later lessons develop other subquery and named-stage forms.
COALESCE(value, 0) chooses the value when it is known and otherwise supplies
zero. Here it handles an absent grouped child under the stated report policy.
It does not identify which underlying facts were duplicated or repair an
incorrect aggregate. If missing amounts meant unknown business data instead,
replacing them with zero would need a different justification.
Run a bounded worked comparison
Use your same owned workspace and supplied session.sh; recheck local context,
resource labels and the marker through check-small.sql. Run the small reset
from the previous lesson first if the dataset has deliberately changed. The
following complete grain-worked.sql contains only checks and SELECT statements.
Its three queries demonstrate the broken report, the corrected report and a
filtered-refund variation. It changes no fixture rows.
\set ON_ERROR_STOP on
\if :{?lab_id}
\else
\echo 'Stop: supply the non-secret lab_id from connection.txt.'
SELECT 1 / 0 AS guard_rejected;
\endif
SELECT current_database() = 'asql_lab'
AND current_user = 'asql_student'
AND current_setting('server_version_num') = '180006' AS target_ok
\gset
\if :target_ok
\else
\echo 'Stop: wrong database, execution role or server release.'
SELECT 1 / 0 AS guard_rejected;
\endif
SET lock_timeout = '3s';
SET statement_timeout = '15s';
SELECT COUNT(*) = 1 AS marker_ok
FROM asql_control.lab
WHERE course_id = 'advanced-sql'
AND lab_id = :'lab_id'
AND fixture_id = 'harbor-small'
\gset
\if :marker_ok
\else
\echo 'Stop: the course marker does not match this lab.'
SELECT 1 / 0 AS guard_rejected;
\endif
-- Deliberately incorrect measures: diagnose the multiplication.
SELECT o.order_id, COUNT(*) AS joined_rows,
SUM(li.amount) AS gross, SUM(r.amount) AS refunded
FROM harbor.orders AS o
LEFT JOIN harbor.line_items AS li ON li.order_id = o.order_id
LEFT JOIN harbor.refunds AS r ON r.order_id = o.order_id
GROUP BY o.order_id
ORDER BY o.order_id;
-- Correct one-row-per-order measures.
SELECT o.order_id, COALESCE(l.gross, 0) AS gross,
COALESCE(r.refunded, 0) AS refunded,
COALESCE(l.gross, 0) - COALESCE(r.refunded, 0) AS net
FROM harbor.orders AS o
LEFT JOIN (
SELECT order_id, SUM(amount) AS gross
FROM harbor.line_items GROUP BY order_id
) AS l ON l.order_id = o.order_id
LEFT JOIN (
SELECT order_id, SUM(amount) AS refunded
FROM harbor.refunds GROUP BY order_id
) AS r ON r.order_id = o.order_id
ORDER BY o.order_id;
-- Preserve all orders while filtering the refund measure.
SELECT o.order_id, COALESCE(r.refunded, 0) AS qualifying_refunds
FROM harbor.orders AS o
LEFT JOIN (
SELECT order_id, SUM(amount) AS refunded
FROM harbor.refunds WHERE amount >= 10 GROUP BY order_id
) AS r ON r.order_id = o.order_id
ORDER BY o.order_id;
Save it in your host lab directory, then execute there:
asql exec -T db psql -X -v ON_ERROR_STOP=1 -v lab_id="$asql_run" \
-U asql_student -d asql_lab < grain-worked.sql
The familiar guard checks this lab and student role before the queries. The host streams the file to the container client; there is no private repository or download dependency. Read each result in the same order as its SELECT.
The first result is deliberately incorrect for monetary reporting:
| order_id | joined_rows | gross | refunded |
|---|---|---|---|
| 101 | 6 | 240.00 | 60.00 |
| 102 | 1 | 30.00 | NULL |
| 103 | 1 | NULL | NULL |
| 104 | 2 | 50.00 | 10.00 |
Order 104 is a useful warning: its gross happens to be right because it has only one refund, while that refund is repeated for both lines. Partial agreement does not make the join valid. The retained row for 103 contributes to COUNT(*) but supplies no known child amount.
The second query separates the child aggregates. The inner l result has gross
groups 101 → 120, 102 → 30 and 104 → 50. The r result has refund groups
101 → 20 and 104 → 5. Each LEFT JOIN can match at most one group per order;
it retains 103 even though neither child produces a group. The outer SELECT
chooses the display policy and subtracts refund from gross.
| order_id | gross | refunded | net |
|---|---|---|---|
| 101 | 120.00 | 20.00 | 100.00 |
| 102 | 30.00 | 0 | 30.00 |
| 103 | 0 | 0 | 0 |
| 104 | 50.00 | 5.00 | 45.00 |
Zero may display as 0 rather than 0.00; compare its exact numeric value and
units, not a formatting string. The report reconciles to gross 200.00, refunded
25.00 and net 175.00, with four order rows.
If the question were only total line charges, a simple aggregate over lines would suffice. The parent-driven report is useful here because the contract also requires orders with no lines. Do not join an unrelated table just because it is available in the schema.
Put a measure's filter at the right boundary
Suppose a consumer asks for all orders, but only refund amounts of at least
10.00. Filtering the raw joined result with WHERE r.amount >= 10 removes
orders whose refund is absent or too small. It also does not solve the existing
line/refund multiplication.
In the third worked query, WHERE amount >= 10 is inside the refund grouping
query. That relationship first selects qualifying facts, then sums them per
order. The parent LEFT JOIN still retains every order. Its output is:
| order_id | qualifying_refunds |
|---|---|
| 101 | 15.00 |
| 102 | 0 |
| 103 | 0 |
| 104 | 0 |
That filter answers a different question from “show only orders with a qualifying refund.” Place a predicate according to the intended result, not a habit of putting every condition at the end of the outer query.
Why an unexplained DISTINCT is not a repair
Lines 15 and 16 are distinct facts for order 104, both worth 25.00.
SUM(DISTINCT li.amount) would count the value 25.00 once, losing a legitimate
charge. It deduplicates equal argument values, not repeated copies of a fact
identified by its key. A SELECT DISTINCT on the final aggregate output cannot
undo a sum that already counted repeated inputs either.
When the row count or total is surprising, identify the key of each contributing fact and trace its appearances through the join. If you intend deduplication of business observations, first state that separate rule; do not infer it merely from equal amounts. The set-semantics lesson examines that distinction further.
Independent variation: add fulfilment evidence
Return all four orders, one row per order, with correct net amount and the number of recorded fulfilment events. Preserve the zero-event order. Use the existing five event rows and the same missing-child report policy. Do not alter fixture rows or use the reference solution before trying it.
State the grain of every input you propose to join. Predict the four output rows and explain why adding a later event should not change gross/refunded amounts. This last condition catches accidental relationship coupling.
Hint 1: The new relationship also needs at most one row per order before it is combined with the two monetary aggregates.
Hint 2: COUNT(*) over the events table counts actual event rows. Its grouped result is absent for an order with no events; apply the declared parent-display policy after the left join.
Answer and reasoning
Save this complete explained solution as grain-solution.sql only after your
attempt. It uses the same checked target and student role:
\set ON_ERROR_STOP on
\if :{?lab_id}
\else
\echo 'Stop: supply the non-secret lab_id from connection.txt.'
SELECT 1 / 0 AS guard_rejected;
\endif
SELECT current_database() = 'asql_lab'
AND current_user = 'asql_student'
AND current_setting('server_version_num') = '180006' AS target_ok
\gset
\if :target_ok
\else
\echo 'Stop: wrong database, execution role or server release.'
SELECT 1 / 0 AS guard_rejected;
\endif
SET lock_timeout = '3s';
SET statement_timeout = '15s';
SELECT COUNT(*) = 1 AS marker_ok
FROM asql_control.lab
WHERE course_id = 'advanced-sql'
AND lab_id = :'lab_id'
AND fixture_id = 'harbor-small'
\gset
\if :marker_ok
\else
\echo 'Stop: the course marker does not match this lab.'
SELECT 1 / 0 AS guard_rejected;
\endif
SELECT o.order_id,
COALESCE(l.gross, 0) - COALESCE(r.refunded, 0) AS net,
COALESCE(e.events, 0) AS events
FROM harbor.orders AS o
LEFT JOIN (
SELECT order_id, SUM(amount) AS gross
FROM harbor.line_items GROUP BY order_id
) AS l ON l.order_id = o.order_id
LEFT JOIN (
SELECT order_id, SUM(amount) AS refunded
FROM harbor.refunds GROUP BY order_id
) AS r ON r.order_id = o.order_id
LEFT JOIN (
SELECT order_id, COUNT(*) AS events
FROM harbor.fulfilment_events GROUP BY order_id
) AS e ON e.order_id = o.order_id
ORDER BY o.order_id;
The e relationship contributes one count per order, so it cannot repeat either
monetary measure. Execute using the same host-file pattern:
asql exec -T db psql -X -v ON_ERROR_STOP=1 -v lab_id="$asql_run" \
-U asql_student -d asql_lab < grain-solution.sql
| order_id | net | events |
|---|---|---|
| 101 | 100.00 | 3 |
| 102 | 30.00 | 1 |
| 103 | 0 | 0 |
| 104 | 45.00 | 1 |
An additional event changes only the count in e. The separate charge/refund
aggregates still read the same facts. Valid alternatives must preserve that
independence, all four parent keys and the stated zero policy. A result that
happens to match these four rows without a defensible grain contract is not
sufficient evidence.
Diagnose differences and leave the lab intact
If 101 reports gross 240.00/refunded 60.00, inspect raw child combinations before changing aggregation syntax. If 103 disappears, inspect inner joins and outer WHERE filters. If 104 reports gross 25.00, inspect value-based deduplication. If values differ in another way, rerun the supplied baseline check before blaming the planner or assuming the input is unchanged.
Both supplied comparison files are read-only and end without an open explicit transaction. Keep the inputs for revision; no row reset is needed merely from running these SELECTs. If you intentionally changed data, use the prior lesson's guarded small reset and check its result. Pause/discard only the identified lab through the connection lesson's complete cleanup; preserve other resources.