smartyfy.mrindigi.com

Databases & SQL Master Course — 181. Retail Revenue and Returns

Lesson 181 Retail Revenue and Returns

Prerequisites and objectives

Complete Lesson 180 and review the earlier concepts named in this lesson. You will compute a bounded fictional retail measure, prevent refund fan-out, distinguish posted and pending refunds, and identify over-refund exceptions. Review join grain, aggregation, integer monetary units, and foreign keys. This exercise is SQL reporting practice, not accounting, tax, or financial-reporting compliance guidance.

Name the measure before calling it revenue

The lab defines gross merchandise value as units multiplied by the historical unit price recorded on each order line. Net merchandise value subtracts posted refund amounts attached to those lines. All values are fictional USD cents. Shipping, tax, discounts, chargebacks, recognition timing, exchange rates, and payment settlement are outside this deliberately narrow definition.

A business may use the phrase net revenue for a materially different measure. Put the formula, statuses, currency, and period attribution beside the report rather than relying on the title. If refunds are reported in their posting period instead of against original orders, a different time model and query are required.

The line is the monetary base grain. Order ten has two lines, and order eleven has one. A line can have multiple refund events. Therefore a direct line-to-refund join changes the row multiplicity before a later SUM sees the original line amount. Recognizing that one-to-many relationship is the central correctness step.

PRAGMA foreign_keys=ON;
CREATE TABLE lab_line181(id INTEGER PRIMARY KEY,order_id INTEGER NOT NULL,units INTEGER NOT NULL CHECK(units>0),unit_cents INTEGER NOT NULL CHECK(unit_cents>=0));
CREATE TABLE lab_refund181(id INTEGER PRIMARY KEY,line_id INTEGER NOT NULL REFERENCES lab_line181(id),cents INTEGER NOT NULL CHECK(cents>0),status TEXT NOT NULL CHECK(status IN ('posted','pending')));
INSERT INTO lab_line181 VALUES(1,10,2,1000),(2,10,1,500),(3,11,1,1000);
INSERT INTO lab_refund181 VALUES(1,1,400,'posted'),(2,1,600,'posted'),(3,3,1000,'posted'),(4,2,100,'pending');
Observed order reconciliation; all amounts are USD cents
Order Gross minus posted refunds Net
10 2500 − 1000 1500
11 1000 − 1000 0

Aggregate each child relation to the join grain

First reduce posted refunds to one row per line identity. Then left join that relation to the line table. A line without a posted refund still contributes its gross amount, with refund zero only because absence under this complete fictional source contract means no posted refund. Unknown or delayed data would need a different status.

Do not use SUM DISTINCT on monetary values to repair multiplication. Two different lines may have the same amount, and both must contribute. Deduplication should follow stable row identities and the intended source grain, not coincidental equality of measured values. A correct-looking total on one fixture can hide a broken formula.

Exercise 1

Establish the independent gross control total.

Worked solution
-- Connection A
SELECT COUNT(*),SUM(units),SUM(units*unit_cents) FROM lab_line181;

There are three lines, four units, and three thousand five hundred cents of gross merchandise value. These controls come from the line relation alone, before any refund join can multiply rows. Keep this baseline available when validating more complex reports.

Exercise 2

Aggregate only posted refund events by line.

Worked solution
-- Connection A
SELECT line_id,COUNT(*),SUM(cents) FROM lab_refund181 WHERE status='posted' GROUP BY line_id ORDER BY line_id;

Line one has two partial refund events totaling one thousand cents; line three has one full refund. The pending event on line two is excluded by the declared measure. Exclusion should be visible in definitions and diagnostics, not an undocumented WHERE clause.

Exercise 3

Join preaggregated refunds and reconcile by order.

Worked solution
-- Connection A
WITH r AS (SELECT line_id,SUM(cents) AS refunded FROM lab_refund181 WHERE status='posted' GROUP BY line_id) SELECT l.order_id,SUM(l.units*l.unit_cents) AS gross_cents,SUM(COALESCE(r.refunded,0)) AS refund_cents,SUM(l.units*l.unit_cents-COALESCE(r.refunded,0)) AS net_cents FROM lab_line181 l LEFT JOIN r ON r.line_id=l.id GROUP BY l.order_id ORDER BY l.order_id;

The correct report preserves each line exactly once. Across the two orders, gross is three thousand five hundred, posted refunds are two thousand, and net is one thousand five hundred cents. The order with a full refund remains in the report with zero net rather than disappearing.

Exercise 4

Expose fan-out and detect an excessive refund in a rollback-only trial.

Worked solution
-- Connection A
SELECT SUM(l.units*l.unit_cents) FROM lab_line181 l LEFT JOIN lab_refund181 r ON r.line_id=l.id AND r.status='posted';
BEGIN;
INSERT INTO lab_refund181 VALUES(5,2,600,'posted');
SELECT l.id,l.units*l.unit_cents,SUM(r.cents) FROM lab_line181 l JOIN lab_refund181 r ON r.line_id=l.id WHERE r.status='posted' GROUP BY l.id HAVING SUM(r.cents)>l.units*l.unit_cents ORDER BY l.id;
ROLLBACK;

The raw join inflates gross to five thousand five hundred cents because line one repeats. The new refund is individually positive but exceeds line two’s charged amount in aggregate. A row-level positivity CHECK cannot enforce that cross-row business rule; the exception report identifies it without silently clipping the value.

Keep currency and lifecycle decisions visible

Never add different currencies merely because both are stored as integers. Partition totals by currency or use an explicit governed conversion process with rate date, rounding, and lineage. This single-currency fixture removes that complication so the join error can be isolated. Integer cents also need realistic bounds to avoid overflow in larger datasets.

Returned units and refunded money are related but distinct events. A refund may be partial, occur without a physical return, or be reversed later. Extending the schema requires a stated lifecycle, stable event identity, and clear treatment of corrections. Do not infer units returned by dividing every refund by a current product price.

For reproducibility, record the source snapshot and cutoff, accepted statuses, line-price meaning, currency, and report version. A future status transition from pending to posted should have a predictable effect under the chosen attribution policy. Test that transition and compare before-and-after controls.

Useful acceptance fixtures include a line with no refund, several partial refunds, a fully refunded order, equal-priced lines, and an over-refund exception. Reconcile both counts and amounts. An aggregate can balance despite two opposing mistakes, so keep row-level diagnostics as well as the grand total.

Pitfalls and summary

Define the measure narrowly, use historical line values, aggregate refund events before joining, and preserve zero-net orders. Treat over-refunds and unknown currency or status as explicit issues rather than hiding them with DISTINCT, clipping, or convenient defaults.

Knowledge check

Question 1

Why does the direct refund join inflate gross?

  1. The query omits quantity multiplication from each line amount
  2. A line with several refund events appears several times
  3. LEFT JOIN removes every unrefunded line
  4. Refunds are matched at order grain rather than line grain
Answer and explanation

B. Join multiplicity repeats the line amount before aggregation.

Question 2

Why is SUM DISTINCT of line amounts an unsafe repair?

  1. Different legitimate lines can have equal amounts
  2. SUM DISTINCT deduplicates by line identity rather than amount
  3. Repeated refund events should always be removed by amount equality
  4. Distinct monetary amounts preserve every line identity
Answer and explanation

A. Value equality is not row identity.

Question 3

Which event contributes to this net measure?

  1. Every pending refund immediately
  2. Only a refund equal to the full line price
  3. A refund whose status is posted
  4. Only the earliest refund event per order
Answer and explanation

C. The contract includes all posted events, including partial refunds.

Question 4

What does the excessive-refund trial demonstrate?

  1. A positive CHECK also limits the total across related rows
  2. Foreign keys cap refund amounts at the parent price
  3. Negative net values must be silently replaced with zero
  4. Positive individual refunds can exceed the line value in aggregate
Answer and explanation

D. Cross-row monetary limits require separate validation or controlled writes.

Question 5

What must change before combining another currency?

  1. Sum all cents and label the total with the most common currency
  2. The measure needs currency grouping or an explicit conversion policy
  3. Cast both currencies to the same integer type
  4. Convert once using an undocumented current exchange rate
Answer and explanation

B. A shared numeric representation does not establish economic equivalence.

Execution scope

These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.

Primary references