Advanced SQL with PostgreSQL / Correct rows and quantities

Repair multiplied report totals

Lesson 4 of 51. Open to read. No account needed.

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

Order 101 has three lines and two refunds, producing six raw line–refund pairs. Separately summarizing each child produces one gross group and one refund group, yielding one correct order row.

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:

LineLine amountRefundRefund amount
1140.00215.00
1140.002215.00
1260.00215.00
1260.002215.00
1320.00215.00
1320.002215.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_idjoined_rowsgrossrefunded
1016240.0060.00
102130.00NULL
1031NULLNULL
104250.0010.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_idgrossrefundednet
101120.0020.00100.00
10230.00030.00
103000
10450.005.0045.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_idqualifying_refunds
10115.00
1020
1030
1040

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_idnetevents
101100.003
10230.001
10300
10445.001

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.

References

46 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 149 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy