Fix a Promotion Join That Silently Drops Sales Rows
SQL & DataModel answerLast updated
Diagnose and repair a multi-table SQL query that loses rows due to a NULL-breaking join, UTC date bucketing, and promotion fan-out inflation.
A retail analytics team tracks seasonal promotions across a chain of garden supply stores. Their reporting query is supposed to return daily sales figures for Mulch products during the Garden Season Promo, broken out by date, store, and product. But when they run it, the result set is much smaller than expected — whole stores seem to vanish from the output.
Schema
orders
| Column | Type |
|---|---|
order_id | BIGINT |
customer_id | BIGINT |
store_id | INT |
order_ts_utc | TIMESTAMP |
order_status | VARCHAR |
order_items
| Column | Type |
|---|---|
order_id | BIGINT |
line_id | INT |
product_id | INT |
quantity | INT |
unit_price | NUMERIC(10,2) |
products
| Column | Type |
|---|---|
product_id | INT |
product_name | VARCHAR |
category | VARCHAR |
promotions
| Column | Type |
|---|---|
promo_id | INT |
promo_name | VARCHAR |
product_id | INT |
store_id | INT NULL |
start_date | DATE |
end_date | DATE |
is_national | BOOLEAN |
stores
| Column | Type |
|---|---|
store_id | INT |
region | VARCHAR |
timezone | VARCHAR |
Business rules
- Analyze orders placed between 2025-03-01 and 2025-05-31.
- Only include orders where
order_status = 'COMPLETED'. - Only include products where
category = 'Mulch'. - All reporting dates must reflect the America/New_York business timezone, regardless of each store's local timezone.
- A promotion is either:
- Store-specific —
promotions.store_idis set and applies only to that store. - National —
promotions.store_idisNULLand applies to every store.
- Store-specific —
Expected output
One row per (order_date_et, store_id, product_id) with:
units_sold— total quantitygross_revenue— totalquantity × unit_price
The buggy query
SELECT
DATE(o.order_ts_utc) AS order_date_et,
s.store_id,
p.product_id,
SUM(oi.quantity) AS units_sold,
SUM(oi.quantity * oi.unit_price) AS gross_revenue
FROM orders o
JOIN order_items oi ON o.order_id = oi.order_id
JOIN products p ON oi.product_id = p.product_id
JOIN promotions pr ON p.product_id = pr.product_id
JOIN stores s ON pr.store_id = s.store_id
WHERE o.order_status = 'COMPLETED'
AND p.category = 'Mulch'
AND pr.promo_name = 'Garden Season Promo'
AND DATE(o.order_ts_utc) BETWEEN pr.start_date AND pr.end_date
AND o.store_id = s.store_id
GROUP BY 1, 2, 3;
Your task
- Explain why this query returns far fewer rows than expected.
- Identify every logical bug — focus on join conditions and date handling.
- Rewrite the query so it correctly captures all qualifying mulch orders, including both store-specific and national promotions.
Hints
Hint 1
What happens when you INNER JOIN on a column that contains NULL values? Trace what `pr.store_id = s.store_id` evaluates to for every national promotion row.
Hint 2
The timestamps are stored in UTC but the business wants Eastern dates. Think about what `DATE(order_ts_utc)` returns for an order placed at 11 PM Eastern time — and what that means at promo window boundaries.
Hint 3
The promotions table is being used as a regular JOIN, which can multiply rows when more than one promo row matches a product. Consider whether you actually need rows from that table, or just a yes/no eligibility check.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Root causes at a glance
There are three independent bugs, each capable of shrinking the result set on its own:
- National promotions are silently removed by an INNER JOIN on a NULL column.
- Dates are bucketed in UTC, so late-evening Eastern orders land on the wrong calendar day.
- The promotion is joined instead of filtered, which can inflate sums when multiple promo rows match and gives no output at all when none match cleanly.
Bug 1 — NULL kills the national promo join (biggest source of row loss)
JOIN stores s ON pr.store_id = s.store_id
For national promotions, pr.store_id is NULL. The expression NULL = s.store_id evaluates to UNKNOWN, and an INNER JOIN only keeps rows where the condition is TRUE. Every national promotion row is silently discarded before the WHERE clause even runs.
The line AND o.store_id = s.store_id then forces the order's store to match the promotion's store, turning the whole query into "store-specific promos only." If the Garden Season Promo is mostly or entirely national, the output shrinks to a handful of rows or zero.
The stores table is not needed here at all. The order's store is already on orders.store_id, and the business timezone is fixed at America/New_York — there is no reason to look up each store's individual timezone.
Bug 2 — UTC bucketing misassigns late-evening orders
DATE(o.order_ts_utc) AS order_date_et
DATE() strips the time and returns the UTC calendar day. Eastern time is UTC−5 (EST) through March 9 and UTC−4 (EDT) after the spring DST transition. An order placed at 9:30 PM Eastern on May 31 is 01:30 UTC on June 1, so it gets grouped under June 1 and excluded from the analysis window. Orders near promo start and end dates are misclassified the same way.
Never hard-code a UTC offset for Eastern time — DST makes it change. Use a named timezone instead:
(o.order_ts_utc AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York')::date
Bug 3 — Join fan-out inflates aggregates
If a product has two matching promotion rows (e.g., one national row and one store-specific row), the join doubles every order line for that product before SUM runs, inflating both units_sold and gross_revenue. The question the query really needs to answer is: "did a qualifying promotion exist for this line?" — a yes/no question that calls for a semi-join (EXISTS), not a row-producing join.
Bug 4 — The analysis window is missing
The 2025-03-01 to 2025-05-31 window appears nowhere in the query. It must be applied to the Eastern-time date, not the raw UTC timestamp.
Corrected query (PostgreSQL)
WITH completed_lines AS (
-- Resolve all joins that are fact-based (order → items → products)
-- and compute the Eastern-time date once, so every subsequent filter
-- uses the same derived value.
SELECT
o.order_id,
o.store_id,
oi.product_id,
oi.quantity,
oi.unit_price,
(o.order_ts_utc AT TIME ZONE 'UTC'
AT TIME ZONE 'America/New_York')::date AS order_date_et
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.order_status = 'COMPLETED'
AND p.category = 'Mulch'
-- Sargable pre-filter on the raw UTC column so an index can be used.
-- EST boundary (UTC-5) for 2025-03-01 and EDT boundary (UTC-4) for 2025-06-01.
AND o.order_ts_utc >= TIMESTAMP '2025-03-01 05:00'
AND o.order_ts_utc < TIMESTAMP '2025-06-01 04:00'
)
SELECT
cl.order_date_et,
cl.store_id,
cl.product_id,
SUM(cl.quantity) AS units_sold,
SUM(cl.quantity * cl.unit_price) AS gross_revenue
FROM completed_lines cl
WHERE cl.order_date_et BETWEEN DATE '2025-03-01' AND DATE '2025-05-31'
AND EXISTS (
SELECT 1
FROM promotions pr
WHERE pr.promo_name = 'Garden Season Promo'
AND pr.product_id = cl.product_id
-- Store-specific match OR national (NULL store_id = applies everywhere)
AND (pr.store_id = cl.store_id OR pr.store_id IS NULL)
AND cl.order_date_et BETWEEN pr.start_date AND pr.end_date
)
GROUP BY cl.order_date_et, cl.store_id, cl.product_id
ORDER BY cl.order_date_et, cl.store_id, cl.product_id;
Why each change matters
| Change | Reason |
|---|---|
AT TIME ZONE 'America/New_York' | Handles DST correctly; no hard-coded offset |
Store from o.store_id, not promotions | orders always has a store; promotions.store_id may be NULL |
EXISTS with OR pr.store_id IS NULL | Semi-join: each line counts once; national promos are included |
ET date filter in WHERE | Applies the analysis window after timezone conversion |
| UTC pre-filter on raw column | Keeps the query index-friendly on large tables |
Explicit GROUP BY column names | More readable and less fragile than positional references |
Complexity
With hash joins throughout, cost is roughly O(O + I + P + R) where O = orders, I = order items, P = products, R = promotions. The EXISTS becomes a hash semi-join on product_id, so each promotions row is visited at most once per probe. Output space is O(G) for the aggregated groups.
Useful indexes: orders(order_status, order_ts_utc) and promotions(promo_name, product_id).
Edge cases worth raising
- Overlapping promo rows (national + store-specific for the same product on the same day):
EXISTSstops at the first match, so the line is still counted once. - Orders from 8 PM–midnight ET, especially at promo boundaries: the named-timezone conversion places them on the correct Eastern date.
- The March 9 DST transition:
America/New_Yorkhandles the 23-hour day automatically; a fixedUTC-4offset would misclassify March 1–8. is_nationalflag vs.store_id IS NULL: these may disagree in real data. Filter bystore_id IS NULLas stated in the business rules and separately audit rows where the flag and the column conflict.- NULL
quantityorunit_price:SUMskips NULLs silently. Decide whether toCOALESCEto zero or surface them as a data quality issue. - Promo windows wider than the analysis period: both date filters run on the same ET date, so the intersection is enforced correctly.
Common mistakes
- Using
stores.timezoneper-store instead of the fixedAmerica/New_Yorkbusiness rule — the problem statement is explicit that reporting uses one timezone. - Replacing the
EXISTSwithDISTINCTto mask fan-out rather than eliminating the root cause; this hides the bug but does not fix the count logic. - Filtering
is_national = TRUEas the national promo check instead ofstore_id IS NULL— the flag may be stale or misset in real data.