KatInterview

Why a Garden Mulch Report Loses Its Non-Promo Days

SQL & DataModel answer
EasyModel answerSQL & Datasqlleft-joinwhere-vs-on

Last 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 to sales.sale_id)
  • line_id (INT), unique within a sale
  • product_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_date
  • mulch_units: all mulch units sold, promo and non-promo
  • mulch_revenue: total mulch revenue
  • promo_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

  1. Explain why this query returns too few rows and units.
  2. Describe a step-by-step process for finding which join or filter loses the rows.
  3. 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.