Why a Garden Mulch Report Loses Its Non-Promo Days
SQL & DataModel answerLast updated
Diagnose a multi-join SQL report that undercounts mulch sales, trace the lost rows step by step, and rewrite it to return all 30 days with correct totals.
A home-improvement retailer wants a daily report on mulch sales and how much of that volume sold during a promotion. The analyst's query joins four tables, but the output has far fewer rows and units than expected.
Schema
All dates share one timezone, and DATE has no time part.
sales
sale_id(BIGINT, PK)sale_date(DATE)store_id(INT)customer_id(BIGINT)
sale_items
sale_id(BIGINT, FK tosales.sale_id)line_id(INT), unique within a saleproduct_id(BIGINT)qty(INT)unit_price(DECIMAL(10,2))
products
product_id(BIGINT, PK)category(VARCHAR)sub_category(VARCHAR)
promotions
promo_id(BIGINT, PK)product_id(BIGINT)start_date(DATE)end_date(DATE)discount_pct(DECIMAL(5,2))
Desired output
One row per day for the last 30 days, with:
sale_datemulch_units: all mulch units sold, promo and non-promomulch_revenue: total mulch revenuepromo_mulch_units: mulch units sold while an applicable promotion was active
Current query
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 s
JOIN sale_items i
ON s.sale_id = i.sale_id
JOIN products pr
ON pr.product_id = i.product_id
LEFT JOIN promotions 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;
Your tasks
- Explain why this query returns too few rows and units.
- Describe a step-by-step process for finding which join or filter loses the rows.
- Write a corrected query that produces the desired output, including mulch sold without any promotion.
Hints
Hint 1
Look at what a LEFT JOIN puts in the promotion columns when no promotion matches, then ask what a WHERE condition on those columns does to such rows.
Hint 2
Count rows after adding each join and filter one at a time, and compare COUNT(*) with the number of distinct (sale_id, line_id) pairs to detect both lost rows and duplicated ones.
Hint 3
For the fix, decide the promo flag per sale line with EXISTS so overlapping promotions cannot duplicate lines, and drive the output from a generated list of 30 dates so empty days still appear.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Why rows disappear
The main culprit is AND p.discount_pct > 0 in the WHERE clause. It refers to promotions, which is the optional side of a LEFT JOIN.
- For a mulch line with no active promotion, the LEFT JOIN keeps the line but sets every
p.*column toNULL. NULL > 0evaluates toUNKNOWN, andWHEREonly keeps rows where the condition is true, so the line is discarded.- The LEFT JOIN has silently become an INNER JOIN. Only promo sales survive.
Consequences: mulch_units always equals promo_mulch_units, non-promo revenue is missing, and any day without an active promotion vanishes entirely.
Other problems worth naming
- Missing days.
GROUP BY sale_dateonly emits days that still have rows. "One row per day for 30 days" needs a date spine. - Join fan-out. If two promotions overlap for the same product and date, each sale line matches twice and units and revenue are double-counted. Fixing the first bug alone can move the error rather than remove it.
- Category matching.
'Mulch'might be stored insub_category, or with different case or trailing spaces. An exact match silently drops those lines. - Orphan products. The inner join to
productsdrops lines whoseproduct_idis missing from the dimension table. - Window boundary.
>= CURRENT_DATE - 30 dayscovers 31 calendar days including today. Choose explicitly between 30 days including today and 30 complete days.
Debugging approach
Add one join or filter at a time and watch where the count drops or jumps. After each step compare COUNT(*) to COUNT(DISTINCT sale_id, line_id). A mismatch means the grain changed.
-- 1. Baseline: sales in the window
SELECT COUNT(*) FROM sales s
WHERE s.sale_date >= CURRENT_DATE - INTERVAL '29' DAY;
-- 2. Add sale_items (count should grow to the number of lines)
SELECT COUNT(*) FROM sales s
JOIN sale_items i ON i.sale_id = s.sale_id
WHERE s.sale_date >= CURRENT_DATE - INTERVAL '29' DAY;
-- 3. Check for orphan products
SELECT COUNT(*) AS total, COUNT(pr.product_id) AS matched
FROM sale_items i
LEFT JOIN products pr ON pr.product_id = i.product_id;
-- 4. Inspect real category values before filtering
SELECT category, sub_category, COUNT(*)
FROM products
WHERE LOWER(category) LIKE '%mulch%' OR LOWER(sub_category) LIKE '%mulch%'
GROUP BY 1, 2;
-- 5. Add LEFT JOIN promotions WITHOUT the WHERE predicate.
-- Count should be >= step 4; strictly greater means fan-out.
-- 6. Add WHERE p.discount_pct > 0 and watch the count collapse to promo-only rows.
A direct fan-out check:
SELECT i.sale_id, i.line_id, COUNT(*) AS n_promos
FROM sales s
JOIN sale_items i ON i.sale_id = s.sale_id
JOIN promotions p ON p.product_id = i.product_id
AND s.sale_date BETWEEN p.start_date AND p.end_date
GROUP BY 1, 2
HAVING COUNT(*) > 1;
Corrected query (PostgreSQL)
Design choices:
- Keep the grain at one row per sale line.
- Compute the promo flag with
EXISTS, so any number of overlapping promotions yields one boolean. - Put the
discount_pctcondition inside theEXISTSsubquery, not in the outerWHERE. - Left-join the daily aggregates onto a 30-day date spine.
WITH days AS (
SELECT CAST(d AS DATE) AS sale_date
FROM generate_series(
CURRENT_DATE - INTERVAL '29' DAY,
CURRENT_DATE,
INTERVAL '1' DAY
) AS g(d)
),
mulch_lines AS (
SELECT s.sale_date, i.product_id, i.qty, i.unit_price
FROM sales s
JOIN sale_items i ON i.sale_id = s.sale_id
JOIN products pr ON pr.product_id = i.product_id
WHERE UPPER(TRIM(pr.category)) = 'MULCH'
AND s.sale_date BETWEEN CURRENT_DATE - INTERVAL '29' DAY AND CURRENT_DATE
),
flagged AS (
SELECT m.*,
CASE WHEN EXISTS (
SELECT 1 FROM promotions p
WHERE p.product_id = m.product_id
AND m.sale_date BETWEEN p.start_date AND p.end_date
AND p.discount_pct > 0
) THEN 1 ELSE 0 END AS is_promo
FROM mulch_lines m
),
daily AS (
SELECT sale_date,
SUM(qty) AS mulch_units,
SUM(qty * unit_price) AS mulch_revenue,
SUM(CASE WHEN is_promo = 1 THEN qty ELSE 0 END) AS promo_mulch_units
FROM flagged
GROUP BY sale_date
)
SELECT d.sale_date,
COALESCE(x.mulch_units, 0) AS mulch_units,
COALESCE(x.mulch_revenue, 0) AS mulch_revenue,
COALESCE(x.promo_mulch_units, 0) AS promo_mulch_units
FROM days d
LEFT JOIN daily x ON x.sale_date = d.sale_date
ORDER BY d.sale_date;
On Snowflake or BigQuery, replace generate_series with a calendar table or GENERATE_DATE_ARRAY.
An alternative is keeping the LEFT JOIN and moving p.discount_pct > 0 into the ON clause. That still fans out on overlapping promotions unless you deduplicate first, so EXISTS is safer.
Why it is correct
- Every mulch line is counted exactly once, because no filter touches a nullable outer-joined column and
EXISTSreturns one value per line. promo_mulch_units <= mulch_unitsby construction, since it is a conditional sum over the same rows. This makes a good sanity assertion.- Exactly 30 rows come back, with zeros on days with no sales.
- Revenue uses the recorded
unit_price, which is already the transaction price. Applyingdiscount_pctagain would discount promo sales twice.
Complexity
With L sale lines in the window and P promotions: hash joins cost O(L). With an index on promotions(product_id, start_date, end_date), each EXISTS probe is about O(log P), so the total is roughly O(L log P). Output memory is O(30).
Edge cases and common mistakes
- Overlapping promotions on the same product and day: handled by
EXISTS. - Promotions with
discount_pctof 0 orNULL: not counted as promo, and state this assumption explicitly. - Moving the filter into
ONbut forgetting that it still allows duplicates. - Using
COUNT(*)after the joins as a "number of sales" metric, which is inflated by the line grain. - Not deciding whether "last 30 days" includes today.