Fixing Outer-Join Row Loss in Daily Mulch Sales
Easy · Data Manipulation (SQL/Python) · Product Analyst · Onsite
Problem Statement
Treat 2025-06-30 as the current date, making the trailing 30-day reporting period 2025-06-01 through 2025-06-30 inclusive. You are auditing a daily merchandising query for products in category = 'Mulch' across four tables (sales, sale_items, products, and promotions).
For every calendar date inside 2025-06-01 .. 2025-06-30 that recorded at least one mulch line item, the report must output one row with:
sale_date: calendar date of the transaction.mulch_units: total quantity (SUM(qty)) across all mulch line items sold on that date, whether promoted or full-price.mulch_revenue: total mulch dollar sales (SUM(qty * unit_price)), rounded to 2 decimal places.promo_mulch_units: total quantity (SUM(qty)) from mulch line items covered by at least one active promotion onsale_date(start_date <= sale_date <= end_dateinclusive) for the sameproduct_idwithdiscount_pct > 0.
An analyst drafted the following SQL query, which returns fewer dates and fewer units than expected:
SELECT
s.sale_date,
SUM(i.qty) AS mulch_units,
SUM(i.qty * i.unit_price) AS mulch_revenue,
SUM(CASE WHEN p.promo_id IS NOT NULL THEN i.qty ELSE 0 END) AS promo_mulch_units
FROM sales AS s
JOIN sale_items AS i
ON s.sale_id = i.sale_id
JOIN products AS pr
ON pr.product_id = i.product_id
LEFT JOIN promotions AS p
ON p.product_id = i.product_id
AND s.sale_date BETWEEN p.start_date AND p.end_date
WHERE pr.category = 'Mulch'
AND p.discount_pct > 0
AND s.sale_date >= CURRENT_DATE - INTERVAL '30' DAY
GROUP BY 1;
Address three questions in your interview walkthrough, with automated grading evaluating your corrected query in Part 3:
- Explain why the draft query drops dates and undercounts units (and what other defects it contains).
- Outline a step-by-step diagnostic procedure (such as staged row and unit counts) to isolate where records are lost or duplicated.
- Write the corrected SQL query assigned to
QUERYreturningsale_date,mulch_units,mulch_revenue, andpromo_mulch_unitsin any row order.
Input Schema
sales
| Column | Type | Description |
|---|---|---|
sale_id |
BIGINT |
Unique receipt identifier (primary key). |
sale_date |
DATE |
Calendar date of the checkout (no time component). |
store_id |
INTEGER |
Store location identifier. |
customer_id |
BIGINT |
Shopper identifier. |
sale_items
| Column | Type | Description |
|---|---|---|
sale_id |
BIGINT |
References sales.sale_id. |
line_id |
INTEGER |
Line number unique within each sale_id. |
product_id |
BIGINT |
References products.product_id. |
qty |
INTEGER |
Units purchased on this receipt line. |
unit_price |
DECIMAL(10,2) |
Realized per-unit checkout price. |
products
| Column | Type | Description |
|---|---|---|
product_id |
BIGINT |
Unique product identifier (primary key). |
category |
VARCHAR |
Top-level department (target rows have 'Mulch'). |
sub_category |
VARCHAR |
Specific product variety. |
promotions
| Column | Type | Description |
|---|---|---|
promo_id |
BIGINT |
Unique promotion identifier (primary key). |
product_id |
BIGINT |
Promoted product identifier. |
start_date |
DATE |
First calendar date the promotion applies (inclusive). |
end_date |
DATE |
Last calendar date the promotion applies (inclusive). |
discount_pct |
DECIMAL(5,2) |
Percentage markdown; only discount_pct > 0 counts as an active discount. |
Examples
Example 1
Input:
sales
sale_id |
sale_date |
store_id |
customer_id |
|---|---|---|---|
10 |
'2025-05-31' |
3 |
2001 |
11 |
'2025-06-03' |
3 |
2002 |
12 |
'2025-06-06' |
4 |
2003 |
13 |
'2025-06-08' |
3 |
2004 |
14 |
'2025-06-08' |
4 |
2005 |
15 |
'2025-06-22' |
5 |
2006 |
sale_items
sale_id |
line_id |
product_id |
qty |
unit_price |
|---|---|---|---|---|
10 |
1 |
501 |
8 |
4.00 |
11 |
1 |
501 |
4 |
4.25 |
11 |
2 |
601 |
1 |
18.00 |
12 |
1 |
501 |
6 |
3.50 |
12 |
2 |
502 |
3 |
4.50 |
13 |
1 |
501 |
2 |
3.20 |
14 |
1 |
601 |
2 |
15.00 |
14 |
2 |
502 |
5 |
4.50 |
15 |
1 |
701 |
3 |
9.00 |
products
product_id |
category |
sub_category |
|---|---|---|
501 |
'Mulch' |
'Cedar Mulch' |
502 |
'Mulch' |
'Black Mulch' |
601 |
'Tools' |
'Shovel' |
701 |
'Plants' |
'Fern' |
promotions
promo_id |
product_id |
start_date |
end_date |
discount_pct |
|---|---|---|---|---|
10 |
501 |
'2025-06-05' |
'2025-06-10' |
15.0 |
11 |
501 |
'2025-06-08' |
'2025-06-12' |
20.0 |
12 |
502 |
'2025-06-01' |
'2025-06-30' |
0.0 |
13 |
601 |
'2025-06-01' |
'2025-06-30' |
10.0 |
Output:
sale_date |
mulch_units |
mulch_revenue |
promo_mulch_units |
|---|---|---|---|
'2025-06-03' |
4 |
17.0 |
0 |
'2025-06-06' |
9 |
34.5 |
6 |
'2025-06-08' |
7 |
28.9 |
2 |
Explanation:
- Sale 10 (2025-05-31) falls outside the 30-day window 2025-06-01 .. 2025-06-30, and Sale 15 (2025-06-22) contains only 'Plants', so neither date appears.
- On 2025-06-03, 4 bags of Cedar Mulch sell before Promo 10 starts (17.0 revenue, 0 promo units); Shovel (601) is ignored.
- On 2025-06-06, 6 bags of Cedar Mulch qualify under Promo 10, while 3 bags of Black Mulch match only 0.0% Promo 12 (counted in total units and revenue, 0 promo units), totaling 9 units, 34.5 revenue, and 6 promo units.
- On 2025-06-08, Sale 13's 2 bags of Cedar Mulch match both overlapping Promos 10 and 11 yet count once (2 promo units, 6.40 revenue), combining with Sale 14's 5 unpromoted bags of Black Mulch (22.50 revenue) for 7 total units and 28.9 revenue.
Example 2
Input:
sales
sale_id |
sale_date |
store_id |
customer_id |
|---|---|---|---|
21 |
'2025-06-01' |
1 |
3001 |
22 |
'2025-06-30' |
2 |
3002 |
sale_items
sale_id |
line_id |
product_id |
qty |
unit_price |
|---|---|---|---|---|
21 |
1 |
501 |
2 |
4.75 |
22 |
1 |
501 |
5 |
4.00 |
products
product_id |
category |
sub_category |
|---|---|---|
501 |
'Mulch' |
'Cedar Mulch' |
promotions
(empty)
Output:
sale_date |
mulch_units |
mulch_revenue |
promo_mulch_units |
|---|---|---|---|
'2025-06-01' |
2 |
9.5 |
0 |
'2025-06-30' |
5 |
20.0 |
0 |
Explanation: Both window endpoints (2025-06-01 and 2025-06-30) are included, and days with zero promotions still report full mulch_units and mulch_revenue alongside promo_mulch_units = 0.
Constraints
- Today is
2025-06-30; include sales wheresale_dateis between'2025-06-01'and'2025-06-30'inclusive. - Filter strictly to items with
products.category = 'Mulch'; omit calendar days that have zero mulch sales. - A promotion applies to a sale line if and only if
promotions.product_id = sale_items.product_id,sale_datelies in[start_date, end_date]inclusive, anddiscount_pct > 0(0andNULLdo not qualify). - Each
(sale_id, line_id)must contribute at most once tomulch_units,mulch_revenue, andpromo_mulch_units, even when multiple promotions overlap. - Round
mulch_revenueto 2 decimal places; output row order does not matter.
Step-by-step walkthrough
Understand the target output and business rules
This interview prompt asks for three deliverables:
- Explain why the existing query loses rows and units.
- Walk through a systematic debugging method to pinpoint which join or filter drops rows.
- Write the corrected SQL query (the graded portion).
Our corrected query must return one row per calendar day (within the last 30 days) that had at least one mulch sale, with four columns:
sale_date: the sale's calendar date (2025-06-01through2025-06-30inclusive, given today is2025-06-30).mulch_units: total units (SUM(qty)) across all mulch sale lines (products.category = 'Mulch'), whether on promotion or not.mulch_revenue: total mulch revenue (SUM(qty * unit_price)), rounded to 2 decimal places.promo_mulch_units: mulch units sold on lines where at least one promotion matched the product, coveredsale_date(start_date .. end_dateinclusive), and haddiscount_pct > 0.
Crucially, every sale line (
sale_id, line_id) must count exactly once, even if two promotions overlap on the same product and date.Why the given query drops rows (and hides two more traps)
Inspect how the original
LEFT JOINandWHEREinteract row by row on Example 1:Mulch sale line LEFT JOIN promotions p WHERE p.discount_pct > 0 --------------------------- ------------------------------ ---------------------------------- Sale 11, prod 501 on 06-03 no active promo -> p.* NULL NULL > 0 is UNKNOWN -> DROPPED! Sale 12, prod 501 on 06-06 Promo 10 matches -> pct = 15.0 15.0 > 0 is TRUE -> kept Sale 12, prod 502 on 06-06 Promo 12 matches -> pct = 0.0 0.0 > 0 is FALSE -> DROPPED! Sale 13, prod 501 on 06-08 Promos 10 & 11 BOTH match kept TWICE -> DOUBLED! Sale 14, prod 502 on 06-08 Promo 12 matches -> pct = 0.0 0.0 > 0 is FALSE -> DROPPED!Three bugs explain the discrepancy:
WHERE p.discount_pct > 0destroys theLEFT JOIN(main row-loss bug). When a mulch line has no active promotion,LEFT JOINkeeps the row and fills everyp.*column withNULL. Immediately afterward,WHERE p.discount_pct > 0evaluatesNULL > 0, which isUNKNOWN(notTRUE) in SQL's three-valued logic (and0.0 > 0isFALSE).WHEREdiscards all non-TRUErows, silently converting theLEFT JOINinto a filteredINNER JOIN! Non-promo units disappear from mixed days (06-06and06-08), and days with zero positive-discount promos (06-03) vanish completely.- Overlapping promotions duplicate sale lines (fan-out trap). Even if you move
p.discount_pct > 0into theLEFT JOIN ... ONclause,promotionsis not unique per(product_id, sale_date). On2025-06-08, Promos10and11both cover product501, so the join outputs Sale13twice, doubling itsqty, revenue, and promo units. - Off-by-one, open-ended date filter. On
2025-06-30,CURRENT_DATE - INTERVAL '30' DAYequals2025-05-31. Including both endpoints05-31 .. 06-30spans 31 days, not 30 (letting Sale10on2025-05-31slip in), and omitting<= '2025-06-30'lets future-dated rows slip in.
Systematic debugging: count rows, distinct lines, and units at each step
Instead of guessing where rows disappear, stack each join and filter into sequential CTEs and measure three invariants after every stage:
n_rows: physical row count at this stage.n_lines:COUNT(DISTINCT sale_id || '-' || line_id). Ifn_rows > n_lines, a join just duplicated sale lines!units:SUM(qty). Any unexpected drop pinpoints the exact step losing volume.
WITH step1 AS ( SELECT sale_id, sale_date FROM sales WHERE sale_date BETWEEN '2025-06-01' AND '2025-06-30' ), step2 AS ( SELECT step1.sale_date, i.sale_id, i.line_id, i.product_id, i.qty FROM step1 JOIN sale_items AS i ON i.sale_id = step1.sale_id ), step3 AS ( SELECT step2.* FROM step2 JOIN products AS pr ON pr.product_id = step2.product_id WHERE pr.category = 'Mulch' ), step4 AS ( SELECT step3.*, p.promo_id, p.discount_pct FROM step3 LEFT JOIN promotions AS p ON p.product_id = step3.product_id AND step3.sale_date BETWEEN p.start_date AND p.end_date ), step5 AS ( SELECT * FROM step4 WHERE discount_pct > 0 ) SELECT '2 sales + sale_items' AS stage, COUNT(*) AS n_rows, COUNT(DISTINCT sale_id || '-' || line_id) AS n_lines, SUM(qty) AS units FROM step2 UNION ALL SELECT '3 + products (Mulch)', COUNT(*), COUNT(DISTINCT sale_id || '-' || line_id), SUM(qty) FROM step3 UNION ALL SELECT '4 + LEFT JOIN promotions', COUNT(*), COUNT(DISTINCT sale_id || '-' || line_id), SUM(qty) FROM step4 UNION ALL SELECT '5 + WHERE discount_pct > 0', COUNT(*), COUNT(DISTINCT sale_id || '-' || line_id), SUM(qty) FROM step5Running that diagnostic on Example 1 makes both culprits unmistakable:
stage n_rows n_lines units -------------------------- ------ ------- ----- 2 sales + sale_items 8 8 26 3 + products (Mulch) 5 5 20 (drops Shovel & Fern as intended) 4 + LEFT JOIN promotions 6 5 22 <-- n_rows > n_lines! Sale 13 duplicated! 5 + WHERE discount_pct > 0 3 2 10 <-- 3 mulch lines dropped right here!In production, also check whether
sale_itemshas orphanproduct_idvalues missing fromproducts(LEFT JOIN products ... WHERE pr.product_id IS NULL) or inconsistent casing/whitespace inproducts.category(SELECT DISTINCT category FROM products).Lock in the grain: one row per mulch sale line
Start from the exact grain we want to sum over — individual mulch
sale_itemslines inside the 30-day window — joining only primary-key tables that can never multiply rows:sale_itemsjoins tosalesonsale_id(primary key ofsales: at most 1 match per line).sale_itemsjoins toproductsonproduct_id(primary key ofproducts: at most 1 match per line).- Filter
pr.category = 'Mulch'ands.sale_date BETWEEN '2025-06-01' AND '2025-06-30'(in PostgreSQL production code,CURRENT_DATE - 29throughCURRENT_DATEgives an exact 30-day inclusive window).
FROM sales AS s JOIN sale_items AS i ON i.sale_id = s.sale_id JOIN products AS pr ON pr.product_id = i.product_id WHERE pr.category = 'Mulch' -- Today is 2025-06-30, so the inclusive 30-day window runs from 2025-06-01 through 2025-06-30 AND s.sale_date BETWEEN '2025-06-01' AND '2025-06-30'Flag applicable promotions with EXISTS instead of joining
Rather than joining
promotions(which risks fan-out), compute a0 / 1columnon_promoper mulch line usingEXISTS:- Preserves non-promo lines: When no valid promotion matches,
EXISTS (...)isFALSE, so theCASEexpression outputs0and the mulch line stays inmulch_lines. - Prevents double-counting: Even if two or three promotions overlap for the same product on
sale_date,EXISTSstops at the first match and outputs a single1without adding rows. - Handles zero/NULL discounts cleanly: Putting
AND p.discount_pct > 0insideEXISTStreats0orNULLdiscounts as "not an applicable promo" (on_promo = 0) while keeping the regular mulch sale intact.
WITH mulch_lines AS ( -- Keep exactly one row per mulch sale item in the 30-day window so units never double-count SELECT s.sale_date, i.qty, i.unit_price, -- Flag whether at least one active positive-discount promo covers this sale line -- EXISTS avoids both dropping non-promo lines and duplicating lines with overlapping promos CASE WHEN EXISTS ( SELECT 1 FROM promotions AS p WHERE p.product_id = i.product_id AND s.sale_date BETWEEN p.start_date AND p.end_date AND p.discount_pct > 0 ) THEN 1 ELSE 0 END AS on_promo- Preserves non-promo lines: When no valid promotion matches,
Aggregate per day and trace Example 1
Because
mulch_lineshas exactly one row per mulch sale item, grouping bysale_dateneeds only straightforwardSUMs (ROUND(..., 2)cleans up binary floating-point noise in SQLite):SELECT sale_date, SUM(qty) AS mulch_units, -- Round daily revenue once after summing to clean up binary floating-point noise in SQLite ROUND(SUM(qty * unit_price), 2) AS mulch_revenue, SUM(CASE WHEN on_promo = 1 THEN qty ELSE 0 END) AS promo_mulch_units FROM mulch_lines GROUP BY sale_dateTrace Example 1 (Sale
10on2025-05-31is outside June, and products601Shovel and701Fern are excluded):sale_id sale_date product_id qty unit_price line_rev on_promo ------- ---------- ---------- --- ---------- -------- ----------------------------------- 11 2025-06-03 501 4 4.25 17.00 0 (Promo 10 starts 06-05) 12 2025-06-06 501 6 3.50 21.00 1 (Promo 10: 06-05..06-10, 15%) 12 2025-06-06 502 3 4.50 13.50 0 (Promo 12 has discount_pct = 0.0) 13 2025-06-08 501 2 3.20 6.40 1 (Promos 10 & 11 overlap -> 1 row) 14 2025-06-08 502 5 4.50 22.50 0 (Promo 12 has discount_pct = 0.0)Grouping by
sale_dateyields all three mulch days and 20 total units:('2025-06-03', 4, 17.0, 0)('2025-06-06', 9, 34.5, 6)('2025-06-08', 7, 28.9, 2)
Complete SQL solution
Here is the complete query:
WITH mulch_lines AS ( -- Keep exactly one row per mulch sale item in the 30-day window so units never double-count SELECT s.sale_date, i.qty, i.unit_price, -- Flag whether at least one active positive-discount promo covers this sale line -- EXISTS avoids both dropping non-promo lines and duplicating lines with overlapping promos CASE WHEN EXISTS ( SELECT 1 FROM promotions AS p WHERE p.product_id = i.product_id AND s.sale_date BETWEEN p.start_date AND p.end_date AND p.discount_pct > 0 ) THEN 1 ELSE 0 END AS on_promo FROM sales AS s JOIN sale_items AS i ON i.sale_id = s.sale_id JOIN products AS pr ON pr.product_id = i.product_id WHERE pr.category = 'Mulch' -- Today is 2025-06-30, so the inclusive 30-day window runs from 2025-06-01 through 2025-06-30 AND s.sale_date BETWEEN '2025-06-01' AND '2025-06-30' ) SELECT sale_date, SUM(qty) AS mulch_units, -- Round daily revenue once after summing to clean up binary floating-point noise in SQLite ROUND(SUM(qty * unit_price), 2) AS mulch_revenue, SUM(CASE WHEN on_promo = 1 THEN qty ELSE 0 END) AS promo_mulch_units FROM mulch_lines GROUP BY sale_date✅ Submit now — all tests should pass.
Intuition & how it works
Think of every mulch line on a cash-register receipt (sale_items) as one paper slip on your desk. You want to sort those slips into daily piles (sale_date), add up every bag sold (mulch_units) and total dollars paid (mulch_revenue), and also tally how many of those bags were sold while a valid discount promotion was active (promo_mulch_units). Instead of stapling promotion rows onto receipt slips — which either throws away unpromoted slips or photocopies slips when two promotions overlap — we stamp each slip once with a 1 ("at least one valid promo active") or 0 ("no valid promo") using EXISTS, and then sum the slips by day.
The original query fails because it LEFT JOINs promotions p and then filters WHERE p.discount_pct > 0. Whenever a mulch receipt line has no matching promotion, LEFT JOIN fills p.discount_pct with NULL; WHERE NULL > 0 evaluates to UNKNOWN rather than TRUE, silently deleting every non-promo mulch line and turning the LEFT JOIN into an INNER JOIN! Simply moving p.discount_pct > 0 into the LEFT JOIN ... ON clause still leaves a second bug: if two promotions overlap for the same product on the same day, the join duplicates that receipt line and inflates units, revenue, and promo units alike.
Trace 2025-06-06 and 2025-06-08 in Example 1: on 2025-06-06, Sale 12 has 6 bags of Cedar Mulch (product_id = 501 at 3.50, covered by 15% Promo 10) and 3 bags of Black Mulch (product_id = 502 at 4.50, matched only by 0% Promo 12). Joining sales, sale_items, and products keeps both receipt lines intact, and EXISTS stamps Cedar Mulch with on_promo = 1 and Black Mulch with on_promo = 0, summing to mulch_units = 6 + 3 = 9, mulch_revenue = 21.0 + 13.5 = 34.5, and promo_mulch_units = 6. Likewise, on 2025-06-08, Sale 13's 2 bags of Cedar Mulch are stamped once (on_promo = 1) even though Promos 10 and 11 overlap, preventing double-counting.
Complexity
Let S, L, P, and R be the total row counts of sales, sale_items, products, and promotions, and let M be the number of mulch sale lines inside the 30-day window (M <= L).
- Time: Joining
sales,sale_items, andproductstakesO(S + L + P)expected time with hash joins (building an in-memory lookup table on the primary-key table and probing it once per line), or even less when an index onsales(sale_date)filters to the 30-day window first and probes an index onsale_items(sale_id). For each of theMmulch lines, the correlatedEXISTSsubquery checks whether a matching promotion exists: with a composite index (an index sorted on multiple columns together) onpromotions(product_id, start_date, end_date), each probe inspects only that product's promotions rather than scanning allRrows (which would takeO(M * R)without an index). Finally,GROUP BY sale_datescans theMmulch lines once and updates at most 30 daily accumulators inO(M)expected time. - Space: Grouping requires
O(D)memory whereD <= 30is the number of active dates in the window, plus hash-join tables proportional to the filteredsalesandproductssets.
Recommended indexes for production scale: sales(sale_date, sale_id), sale_items(sale_id, product_id), products(product_id) (primary key), and promotions(product_id, start_date, end_date).
Edge cases
- Regular-price mulch lines (no matching promotion):
EXISTSreturnsFALSE(on_promo = 0), keeping the units inmulch_unitsandmulch_revenuewhile adding0topromo_mulch_units. - Days with mulch sales and zero promotions: Preserved as output rows with
promo_mulch_units = 0(2025-06-03in Example 1, and both2025-06-01and2025-06-30in Example 2). - Overlapping promotions on the same product and date: Counted once per sale line because
EXISTSreturns a single boolean result rather than joining multiple rows. - Promotions with
discount_pct = 0orNULL: Excluded byp.discount_pct > 0insideEXISTS, so the line still counts as a regular mulch sale (on_promo = 0). - Exact boundary dates: Both
s.sale_date BETWEEN '2025-06-01' AND '2025-06-30'ands.sale_date BETWEEN p.start_date AND p.end_dateare inclusive at both ends because all columns are calendarDATEs with no time component (2025-05-31and2025-07-01are excluded). - Promotions on non-mulch items in the same basket: Ignored because
p.product_id = i.product_idchecks the mulch line's ownproduct_id. - Days with only non-mulch sales (or empty tables): Produce no row, matching the specification of one row per day that has mulch sales.
Common mistakes
- Filtering a
LEFT JOINed column inWHERE(WHERE p.discount_pct > 0orWHERE p.promo_id IS NOT NULL): RejectsNULL-extended outer-join rows and turns theLEFT JOINinto anINNER JOIN. - Moving
p.discount_pct > 0intoONwithout deduplicating promotions: Preserves non-promo lines, yet double-counts any sale line covered by two overlapping promotions. - Trying to fix join fan-out with
SUM(DISTINCT i.qty): Accidentally collapses two legitimate sale lines that happen to have the same quantity (qty = 2on two receipts sums to2instead of4). - 31-day fencepost error (
sale_date >= CURRENT_DATE - INTERVAL '30' DAY): Counting fromT - 30throughTinclusive covers 31 days (30 - 0 + 1 = 31); a 30-day window ending today starts atCURRENT_DATE - INTERVAL '29' DAY(and should include<= CURRENT_DATE). - Re-discounting
unit_pricein SQL: In retail point-of-sale schemas,sale_items.unit_priceis ordinarily the realized transaction price paid at checkout; multiplying by(1 - discount_pct / 100)would apply the discount twice unlessunit_priceis explicitly documented as list price.
Follow-up questions
-
Why does moving p.discount_pct > 0 from WHERE into the LEFT JOIN ... ON predicate still leave a bug? Moving the predicate into
ONrescues non-promo mulch rows, yetpromotionshas no uniqueness constraint per(product_id, sale_date). Whenever two promotions overlap on the same product and date (as Promos10and11do on2025-06-08for product501in Example 1),LEFT JOIN promotionsemits 2 rows for Sale13's single line item and inflates2units (6.40revenue) into4units (12.80revenue) — whereasEXISTSalways preserves exact one-row-per-line grain. -
How would you emit all 30 calendar dates from 2025-06-01 through 2025-06-30 with zero values on days that had no mulch sales? Generate a 30-row calendar spine (a continuous table of every date in the window, using a recursive CTE in SQLite or
generate_seriesin PostgreSQL) andLEFT JOINthe daily mulch aggregates onto the calendar, wrapping each metric inCOALESCE(..., 0):
sql
WITH RECURSIVE calendar(day) AS (
SELECT '2025-06-01'
UNION ALL
SELECT DATE(day, '+1 day')
FROM calendar
WHERE day < '2025-06-30'
),
mulch_lines AS (
SELECT
s.sale_date,
i.qty,
i.unit_price,
CASE
WHEN EXISTS (
SELECT 1
FROM promotions AS p
WHERE p.product_id = i.product_id
AND s.sale_date BETWEEN p.start_date AND p.end_date
AND p.discount_pct > 0
) THEN 1
ELSE 0
END AS on_promo
FROM sales AS s
JOIN sale_items AS i ON i.sale_id = s.sale_id
JOIN products AS pr ON pr.product_id = i.product_id
WHERE pr.category = 'Mulch'
AND s.sale_date BETWEEN '2025-06-01' AND '2025-06-30'
),
daily AS (
SELECT
sale_date,
SUM(qty) AS mulch_units,
ROUND(SUM(qty * unit_price), 2) AS mulch_revenue,
SUM(CASE WHEN on_promo = 1 THEN qty ELSE 0 END) AS promo_mulch_units
FROM mulch_lines
GROUP BY sale_date
)
SELECT
c.day AS sale_date,
COALESCE(d.mulch_units, 0) AS mulch_units,
COALESCE(d.mulch_revenue, 0) AS mulch_revenue,
COALESCE(d.promo_mulch_units, 0) AS promo_mulch_units
FROM calendar AS c
LEFT JOIN daily AS d
ON d.sale_date = c.day
ORDER BY c.day
- How would you measure whether a mulch discount campaign actually drove incremental category demand rather than shifting baseline purchases? High
promo_mulch_unitsalone does not establish causality because warm weekends naturally boost lawn-and-garden traffic. Compare promoted mulch SKUs against unpromoted garden baselines (difference-in-differences) or run matched-market store holdouts on future promos, and decompose three retail effects: pull-forward (shoppers stocking up early, creating a post-promo dip), cannibalization (promoted Cedar Mulch stealing volume from full-price Black Mulch rather than expanding total category bags), and gross margin dollar impact (whether incremental volume more than offset the per-bag markdown).
Follow-up questions
- Why does moving p.discount_pct > 0 from WHERE into the LEFT JOIN ... ON predicate still leave a bug?
- How would you emit all 30 calendar dates from 2025-06-01 through 2025-06-30 with zero values on days that had no mulch sales?
- How would you measure whether a mulch discount campaign actually drove incremental category demand rather than shifting baseline purchases?
Similar questions
- Fixing Timezone and National-Promo Join Bugs
- Evaluating a Below-Cost Seasonal Retail Promotion
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months