Fixing Timezone and National-Promo Join Bugs
Medium · Data Manipulation (SQL/Python) · Data Analyst · Onsite
Problem Statement
You are auditing a promotional revenue query across five retail tables (orders, order_items, products, promotions, and stores). The report must summarize daily promotional mulch sales under 'Spring Mulch Promo' using the following business rules:
- Reporting window:
2025-03-01through2025-05-31inclusive, evaluated on theAmerica/New_Yorkcalendar date (order_date_et). - Eligible orders & items: Include only orders with
order_status = 'DELIVERED'and line items whose product hascategory = 'Mulch'. - Promotion coverage: A line item qualifies when at least one
'Spring Mulch Promo'row matches itsproduct_id, coversorder_date_et(start_date <= order_date_et <= end_dateinclusive), and applies either to that order's specific store (promotions.store_id = orders.store_id) or nationwide (promotions.store_id IS NULL). - Required output: One row per
(order_date_et, store_id, product_id)reportingunits_sold = SUM(quantity)andgross_revenue = SUM(quantity * unit_price)(rounded to 2 decimal places), counting each qualifying order line at most once.
Below is the faulty query currently in production, which drops a large share of expected rows:
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 AS o
JOIN order_items AS oi
ON o.order_id = oi.order_id
JOIN products AS p
ON oi.product_id = p.product_id
JOIN promotions AS pr
ON p.product_id = pr.product_id
JOIN stores AS s
ON pr.store_id = s.store_id
WHERE o.order_status = 'DELIVERED'
AND p.category = 'Mulch'
AND pr.promo_name = 'Spring Mulch 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;
Cover three points in your walkthrough, with automated grading testing your rewritten SQL query in Part 3:
- Explain why the join chain discards valid rows.
- Identify every join, grain, and timezone/date defect in the original query.
- Write the corrected SQL query assigned to
QUERYreturningorder_date_et,store_id,product_id,units_sold, andgross_revenuein any row order.
Input Schema
orders
| Column | Type | Description |
|---|---|---|
order_id |
BIGINT |
Unique order identifier. |
customer_id |
BIGINT |
Customer identifier. |
store_id |
INTEGER |
Store where the order was placed. |
order_ts_utc |
TIMESTAMP |
Order timestamp recorded in UTC ('YYYY-MM-DD HH:MM:SS'). |
order_status |
VARCHAR |
Fulfillment state (for example, 'DELIVERED', 'CANCELLED'). |
order_items
| Column | Type | Description |
|---|---|---|
order_id |
BIGINT |
References orders.order_id. |
line_id |
INTEGER |
Line number within the order. |
product_id |
INTEGER |
References products.product_id. |
quantity |
INTEGER |
Units purchased on this line. |
unit_price |
DECIMAL(10,2) |
Per-unit transaction price. |
products
| Column | Type | Description |
|---|---|---|
product_id |
INTEGER |
Unique product identifier. |
product_name |
VARCHAR |
Display name of the item. |
category |
VARCHAR |
Product category (target items have 'Mulch'). |
promotions
| Column | Type | Description |
|---|---|---|
promo_id |
INTEGER |
Unique promotion identifier. |
promo_name |
VARCHAR |
Campaign name (target campaign is 'Spring Mulch Promo'). |
product_id |
INTEGER |
Covered product identifier. |
store_id |
INTEGER |
Covered store identifier, or NULL when the promotion applies nationwide. |
start_date |
DATE |
First Eastern calendar date of the promotion (inclusive). |
end_date |
DATE |
Final Eastern calendar date of the promotion (inclusive). |
is_national |
BOOLEAN |
Boolean indicator for nationwide promotions. |
stores
| Column | Type | Description |
|---|---|---|
store_id |
INTEGER |
Unique store identifier. |
region |
VARCHAR |
Geographic division. |
timezone |
VARCHAR |
Local IANA timezone of the physical store. |
Examples
Example 1
Input:
stores
store_id |
region |
timezone |
|---|---|---|
10 |
'East' |
'America/New_York' |
20 |
'South' |
'America/New_York' |
30 |
'Central' |
'America/Chicago' |
products
product_id |
product_name |
category |
|---|---|---|
301 |
'Cedar Mulch Bag' |
'Mulch' |
302 |
'Pine Bark Mulch' |
'Mulch' |
401 |
'Pruning Shears' |
'Tools' |
promotions
promo_id |
promo_name |
product_id |
store_id |
start_date |
end_date |
is_national |
|---|---|---|---|---|---|---|
11 |
'Spring Mulch Promo' |
301 |
10 |
'2025-03-01' |
'2025-04-15' |
False |
12 |
'Spring Mulch Promo' |
302 |
NULL |
'2025-04-10' |
'2025-05-31' |
True |
13 |
'Memorial Patio Sale' |
401 |
NULL |
'2025-05-01' |
'2025-05-31' |
True |
orders
order_id |
customer_id |
store_id |
order_ts_utc |
order_status |
|---|---|---|---|---|
2001 |
801 |
10 |
'2025-03-05 03:30:00' |
'DELIVERED' |
2002 |
802 |
10 |
'2025-03-04 18:00:00' |
'DELIVERED' |
2003 |
803 |
10 |
'2025-04-16 02:15:00' |
'DELIVERED' |
2004 |
804 |
20 |
'2025-04-12 16:00:00' |
'DELIVERED' |
2005 |
805 |
30 |
'2025-05-20 20:00:00' |
'CANCELLED' |
2006 |
806 |
30 |
'2025-06-01 02:45:00' |
'DELIVERED' |
order_items
order_id |
line_id |
product_id |
quantity |
unit_price |
|---|---|---|---|---|
2001 |
1 |
301 |
4 |
3.75 |
2001 |
2 |
401 |
1 |
19.00 |
2002 |
1 |
301 |
2 |
3.75 |
2003 |
1 |
301 |
5 |
3.60 |
2004 |
1 |
302 |
3 |
4.20 |
2004 |
2 |
301 |
2 |
3.75 |
2005 |
1 |
302 |
7 |
4.20 |
2006 |
1 |
302 |
2 |
4.20 |
Output:
order_date_et |
store_id |
product_id |
units_sold |
gross_revenue |
|---|---|---|---|---|
'2025-03-04' |
10 |
301 |
6 |
22.5 |
'2025-04-12' |
20 |
302 |
3 |
12.6 |
'2025-04-15' |
10 |
301 |
5 |
18.0 |
'2025-05-31' |
30 |
302 |
2 |
8.4 |
Explanation:
- Before US Daylight Saving Time begins on 2025-03-09 07:00:00 UTC, America/New_York is UTC-5 (EST): Order 2001 (2025-03-05 03:30:00 UTC = 2025-03-04 22:30 EST) joins Order 2002 on '2025-03-04' for 4 + 2 = 6 units (22.5 revenue); Pruning Shears (401) are excluded.
- Order 2003 (2025-04-16 02:15:00 UTC = 2025-04-15 22:15 EDT, UTC-4) lands on the final day of Store 10's Promo 11 (5 units, 18.0 revenue).
- Order 2004 at Store 20 keeps Pine Bark Mulch 302 via nationwide Promo 12 (store_id IS NULL), while dropping Cedar Mulch 301 (covered only at Store 10).
- Order 2005 is 'CANCELLED', while Order 2006 (2025-06-01 02:45:00 UTC = 2025-05-31 22:45 EDT) falls inside '2025-03-01' .. '2025-05-31' and matches nationwide Promo 12 at Store 30.
Example 2
Input:
stores: [(10, 'East', 'America/New_York')]
products: [(301, 'Cedar Mulch Bag', 'Mulch')]
promotions:
- (21, 'Spring Mulch Promo', 301, 10, '2025-04-01', '2025-04-30', False)
- (22, 'Spring Mulch Promo', 301, NULL, '2025-04-01', '2025-04-30', True)
orders: [(3001, 901, 10, '2025-04-18 15:00:00', 'DELIVERED')]
order_items: [(3001, 1, 301, 4, 3.50)]
Output:
order_date_et |
store_id |
product_id |
units_sold |
gross_revenue |
|---|---|---|---|---|
'2025-04-18' |
10 |
301 |
4 |
14.0 |
Explanation: Although both a store-specific promotion (21) and a nationwide promotion (22) cover product 301 at Store 10 on 2025-04-18, the order line is counted once (4 units, 14.0 revenue).
Constraints
- Convert every
order_ts_utctimestamp toAmerica/New_York(EST = UTC-5prior to2025-03-09 07:00:00UTC;EDT = UTC-4from2025-03-09 07:00:00UTC onward through the end of May 2025), regardless ofstores.timezone. - Enforce
order_date_et BETWEEN '2025-03-01' AND '2025-05-31'inclusive,order_status = 'DELIVERED',products.category = 'Mulch', andpromotions.promo_name = 'Spring Mulch Promo'. - Match promotions where
promotions.product_id = order_items.product_id,order_date_et BETWEEN start_date AND end_dateinclusive, and(promotions.store_id = orders.store_id OR promotions.store_id IS NULL). - Count each qualifying
(order_id, line_id)once even when multiple promotion rows apply; roundgross_revenueto 2 decimal places. Row order does not matter.
Step-by-step walkthrough
Understand the goal and the business rules
This interview prompt has three parts: explain why rows disappear after the joins, identify all join and date-handling bugs, and write the corrected SQL query (the graded part).
We want one summary row per
(order_date_et, store_id, product_id)reportingunits_sold = SUM(quantity)andgross_revenue = ROUND(SUM(quantity * unit_price), 2)for order lines that satisfy every rule below:orders.order_status = 'DELIVERED'.products.category = 'Mulch'.- The order's calendar date in
America/New_York(order_date_et) falls in2025-03-01 .. 2025-05-31inclusive. - At least one
'Spring Mulch Promo'row covers that product onorder_date_et(start_date .. end_dateinclusive) and applies either to that specific store (pr.store_id = o.store_id) or nationwide (pr.store_id IS NULL). - Each order line counts at most once, even if both a store-specific promo and a national promo match it.
Why the buggy query loses rows: the five bugs
Trace the original
FROMandWHEREclauses to see how each bug drops or distorts rows:Buggy clause What goes wrong ------------------------------------------ -------------------------------------------------------- JOIN stores s ON pr.store_id = s.store_id NULL = store_id is UNKNOWN -> drops ALL national promos! WHERE o.store_id = s.store_id Routes store_id via pr.store_id -> only store promos work DATE(o.order_ts_utc) Uses UTC date -> late-evening NY orders jump to next day (missing 2025-03-01 .. 2025-05-31 filter) Promo dates in Feb or Jun leak out-of-window orders in JOIN promotions pr Overlapping store + national promos double-count linesJOIN stores s ON pr.store_id = s.store_idwipes out every national promotion (biggest row loss). National promotions storeNULLinpromotions.store_id. BecauseNULL = s.store_idevaluates toUNKNOWN(neverTRUE), the inner join immediately deletes every national promotion row! In Example 1, Pine Bark Mulch (302) is promoted nationally, so every single Pine Bark Mulch order vanishes.store_idis routed throughpromotionsinstead oforders. Selectings.store_id(joined topr.store_id) and filteringo.store_id = s.store_idleaves no way for aNULLpromo store to match every order store.DATE(o.order_ts_utc)uses UTC instead ofAmerica/New_York. New York sits 5 hours behind UTC in winter (EST) and 4 hours behind UTC during Daylight Saving Time (EDT). An order placed at22:15EDT on April 15 (2025-04-16 02:15:00UTC, Order2003in Example 1) gets dated2025-04-16in UTC — pushing it past an April 15 promoend_dateand dropping it (while Order2001at2025-03-05 03:30:00UTC gets split onto2025-03-05instead of2025-03-04EST)!- The
2025-03-01 .. 2025-05-31analysis window is missing. If a'Spring Mulch Promo'runs until June 15, June orders slip into the output. - Joining
promotionsdirectly causes join fan-out. Whenever both a store promo and a national promo (as in Example 2) cover the same line,JOIN promotionsemits two rows for one item and doublesunits_soldandgross_revenue.
On Example 1, these bugs lose all national promo orders, drop Order
2003, and misdate Order2001onto2025-03-05.Isolate the row loss step by step
To debug systematically without guessing, chain one join or filter per CTE and inspect row count, distinct
(order_id, line_id)count, andSUM(quantity)at every stage:WITH j1 AS ( SELECT o.order_id, o.store_id AS order_store, o.order_ts_utc, o.order_status, oi.line_id, oi.product_id, oi.quantity FROM orders AS o JOIN order_items AS oi ON o.order_id = oi.order_id ), j2 AS ( SELECT j1.* FROM j1 JOIN products AS p ON j1.product_id = p.product_id WHERE p.category = 'Mulch' ), j3 AS ( SELECT j2.*, pr.promo_name, pr.store_id AS promo_store, pr.start_date, pr.end_date FROM j2 JOIN promotions AS pr ON j2.product_id = pr.product_id ), j4 AS ( SELECT j3.* FROM j3 JOIN stores AS s ON j3.promo_store = s.store_id ), j5 AS ( SELECT * FROM j4 WHERE order_status = 'DELIVERED' AND promo_name = 'Spring Mulch Promo' ), j6 AS ( SELECT * FROM j5 WHERE DATE(order_ts_utc) BETWEEN start_date AND end_date AND order_store = promo_store ) SELECT '1 orders + order_items' AS stage, COUNT(*) AS n_rows, COUNT(DISTINCT order_id || '-' || line_id) AS n_lines, SUM(quantity) AS units FROM j1 UNION ALL SELECT '2 + products (Mulch)', COUNT(*), COUNT(DISTINCT order_id || '-' || line_id), SUM(quantity) FROM j2 UNION ALL SELECT '3 + promotions', COUNT(*), COUNT(DISTINCT order_id || '-' || line_id), SUM(quantity) FROM j3 UNION ALL SELECT '4 + stores ON pr.store_id', COUNT(*), COUNT(DISTINCT order_id || '-' || line_id), SUM(quantity) FROM j4 UNION ALL SELECT '5 + status & promo name', COUNT(*), COUNT(DISTINCT order_id || '-' || line_id), SUM(quantity) FROM j5 UNION ALL SELECT '6 + UTC date & same store', COUNT(*), COUNT(DISTINCT order_id || '-' || line_id), SUM(quantity) FROM j6On Example 1, the drop-offs point straight to the two culprits:
stage n_rows n_lines units -------------------------- ------ ------- ----- 1 orders + order_items 8 8 26 2 + products (Mulch) 7 7 25 (drops Pruning Shears) 3 + promotions 7 7 25 4 + stores ON pr.store_id 4 4 13 <-- loses 12 units (all national promos!) 5 + status & promo name 4 4 13 6 + UTC date & same store 2 2 6 <-- loses Order 2003 due to UTC date!Convert UTC timestamps to New York calendar dates
Every date check — the reporting column, the
2025-03-01 .. 2025-05-31window, and the promotionstart_date .. end_datecheck — must use theAmerica/New_Yorkcalendar date, so computeorder_date_etonce up front.- In PostgreSQL: write
(o.order_ts_utc AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York')::date, which consults the IANA timezone database automatically. - In SQLite: there is no built-in timezone database, so we apply the exact US Eastern offset. In 2025, Daylight Saving Time starts on the second Sunday of March (
2025-03-09) at02:00EST, which is2025-03-09 07:00:00UTC, and does not end until November 2 (long after May 31):
UTC timestamp Offset New York local time order_date_et ----------------------- --------- ---------------------- ------------- 2025-03-05 04:30:00 -5 hours 2025-03-04 23:30 (EST) 2025-03-04 2025-03-09 06:59:59 -5 hours 2025-03-09 01:59 (EST) 2025-03-09 2025-03-09 07:00:00 -4 hours 2025-03-09 03:00 (EDT) 2025-03-09 2025-05-01 03:00:00 -4 hours 2025-04-30 23:00 (EDT) 2025-04-30Notice why a hardcoded
'-4 hours'would misdate2025-03-05 04:30:00UTC as2025-03-05(00:30) instead of2025-03-04(23:30EST)!DATE( o.order_ts_utc, -- America/New_York is EST (UTC-5) before 2025-03-09 07:00 UTC, then EDT (UTC-4) CASE WHEN o.order_ts_utc < '2025-03-09 07:00:00' THEN '-5 hours' ELSE '-4 hours' END ) AS order_date_et,- In PostgreSQL: write
Build one clean row per delivered mulch line
In
order_lines, join onlyorders,order_items, andproducts— primary-key joins that preserve exact one-row-per-order-line grain:- Take
o.store_iddirectly fromorders(where the order occurred). - Do not join
storesat all: none of its columns appear in the output, and the business timezone is fixed toAmerica/New_Yorkfor company-wide reporting (even for Store30inAmerica/Chicago). - Filter
o.order_status = 'DELIVERED'andp.category = 'Mulch'right away.
WITH order_lines AS ( -- Keep one row per delivered mulch line and convert UTC timestamps to New York dates SELECT DATE( o.order_ts_utc, -- America/New_York is EST (UTC-5) before 2025-03-09 07:00 UTC, then EDT (UTC-4) CASE WHEN o.order_ts_utc < '2025-03-09 07:00:00' THEN '-5 hours' ELSE '-4 hours' END ) AS order_date_et, -- Take store_id from the order itself, never routed through promotions o.store_id, oi.product_id, oi.quantity, oi.unit_price FROM orders AS o JOIN order_items AS oi ON oi.order_id = o.order_id JOIN products AS p ON p.product_id = oi.product_id WHERE o.order_status = 'DELIVERED' AND p.category = 'Mulch' )- Take
Match store-specific and national promotions with EXISTS
Now filter
order_linesto the2025-03-01 .. 2025-05-31New York window and check promotion coverage withEXISTS:EXISTSasks a pure yes/no question ("does at least one matching'Spring Mulch Promo'cover this line?"), so overlapping store and national promos never duplicate rows.(pr.store_id = l.store_id OR pr.store_id IS NULL)must be wrapped in parentheses! In SQL,ANDbinds tighter thanOR. Without parentheses,A AND B AND pr.store_id = l.store_id OR pr.store_id IS NULL AND Dsplits atOR, allowing any national promotion active on that date (even'Memorial Patio Sale') to match!- Because
l.order_date_et,pr.start_date, andpr.end_dateare allDATEvalues without timestamps,BETWEEN pr.start_date AND pr.end_dateincludes the entire final day of the promotion.
SELECT l.order_date_et, l.store_id, l.product_id, SUM(l.quantity) AS units_sold, ROUND(SUM(l.quantity * l.unit_price), 2) AS gross_revenue FROM order_lines AS l -- Enforce the business reporting window on the New York calendar date WHERE l.order_date_et BETWEEN '2025-03-01' AND '2025-05-31' -- EXISTS counts each line once even when a store promo and a national promo overlap AND EXISTS ( SELECT 1 FROM promotions AS pr WHERE pr.product_id = l.product_id AND pr.promo_name = 'Spring Mulch Promo' -- Parentheses are critical: match either this order's store or a national promo (NULL) AND (pr.store_id = l.store_id OR pr.store_id IS NULL) AND l.order_date_et BETWEEN pr.start_date AND pr.end_date ) GROUP BY l.order_date_et, l.store_id, l.product_idTrace Example 1 row by row
Orders
2001and2002precede2025-03-09 07:00:00UTC so EST (-5 hours) applies, while Orders2003..2006use EDT (-4 hours):order store order_ts_utc order_date_et prod qty price decision ----- ----- ------------------- ------------- ---- --- ----- --------------------------------------- 2001 10 2025-03-05 03:30:00 2025-03-04 301 4 3.75 KEEP (EST shifts to 03-04; Store 10 promo) 2001 10 2025-03-05 03:30:00 2025-03-04 401 1 19.00 drop (Tools, not Mulch) 2002 10 2025-03-04 18:00:00 2025-03-04 301 2 3.75 KEEP (combines with Order 2001 on 03-04) 2003 10 2025-04-16 02:15:00 2025-04-15 301 5 3.60 KEEP (04-15 EDT is inside 03-01..04-15!) 2004 20 2025-04-12 16:00:00 2025-04-12 302 3 4.20 KEEP (national promo covers Store 20) 2004 20 2025-04-12 16:00:00 2025-04-12 301 2 3.75 drop (301 promo is Store 10 only) 2005 30 2025-05-20 20:00:00 2025-05-20 302 7 4.20 drop (CANCELLED) 2006 30 2025-06-01 02:45:00 2025-05-31 302 2 4.20 KEEP (05-31 EDT is inside May window!)Grouping by
(order_date_et, store_id, product_id)produces all four expected rows:('2025-03-04', 10, 301, 6, 22.5)('2025-04-12', 20, 302, 3, 12.6)('2025-04-15', 10, 301, 5, 18.0)('2025-05-31', 30, 302, 2, 8.4)
Complete SQL solution
Here is the complete query:
WITH order_lines AS ( -- Keep one row per delivered mulch line and convert UTC timestamps to New York dates SELECT DATE( o.order_ts_utc, -- America/New_York is EST (UTC-5) before 2025-03-09 07:00 UTC, then EDT (UTC-4) CASE WHEN o.order_ts_utc < '2025-03-09 07:00:00' THEN '-5 hours' ELSE '-4 hours' END ) AS order_date_et, -- Take store_id from the order itself, never routed through promotions o.store_id, oi.product_id, oi.quantity, oi.unit_price FROM orders AS o JOIN order_items AS oi ON oi.order_id = o.order_id JOIN products AS p ON p.product_id = oi.product_id WHERE o.order_status = 'DELIVERED' AND p.category = 'Mulch' ) SELECT l.order_date_et, l.store_id, l.product_id, SUM(l.quantity) AS units_sold, ROUND(SUM(l.quantity * l.unit_price), 2) AS gross_revenue FROM order_lines AS l -- Enforce the business reporting window on the New York calendar date WHERE l.order_date_et BETWEEN '2025-03-01' AND '2025-05-31' -- EXISTS counts each line once even when a store promo and a national promo overlap AND EXISTS ( SELECT 1 FROM promotions AS pr WHERE pr.product_id = l.product_id AND pr.promo_name = 'Spring Mulch Promo' -- Parentheses are critical: match either this order's store or a national promo (NULL) AND (pr.store_id = l.store_id OR pr.store_id IS NULL) AND l.order_date_et BETWEEN pr.start_date AND pr.end_date ) GROUP BY l.order_date_et, l.store_id, l.product_id✅ Submit now — all tests should pass.
Intuition & how it works
Imagine every delivered mulch item on a customer receipt carries a timestamp from a server clock set to UTC (Coordinated Universal Time, the zero-offset reference clock used by backend systems) along with the store number where it was bought. Before checking whether a bag of mulch qualified for the Spring Mulch Promo, you first translate that UTC clock to the company's headquarters calendar in America/New_York (order_date_et) so evening shoppers are credited to the right business day. Then, instead of joining promotion rows directly to receipt lines, you ask a single yes/no question (EXISTS) per line: did at least one 'Spring Mulch Promo' cover this product on that New York date, either for this specific store or nationwide (store_id IS NULL)?
The original query drops most of its rows for two main reasons. First, it INNER JOINs promotions pr to stores s on pr.store_id = s.store_id: because national promotions store NULL in pr.store_id and NULL = s.store_id is never TRUE in SQL, every national promotion is wiped out! Second, calling DATE(o.order_ts_utc) without converting to New York time shifts any order placed after 7 PM EST (or 8 PM EDT) onto the next UTC date, pushing final-evening sales past end_date (and past May 31), while joining promotions directly also risks double-counting lines when store and national promos overlap.
Look at two concrete orders from Example 1: Order 2003 at Store 10 buys 5 bags of Cedar Mulch (301) at 2025-04-16 02:15:00 UTC, and Order 2004 at Store 20 buys 3 bags of Pine Bark Mulch (302) at 2025-04-12 16:00:00 UTC. Subtracting the 4-hour EDT offset converts Order 2003 to 2025-04-15 (22:15 EDT), rescuing it onto the final day of Store 10's 03-01 .. 04-15 promo (5 units, 18.0 gross revenue), while (pr.store_id = l.store_id OR pr.store_id IS NULL) inside EXISTS lets Order 2004 match Pine Bark Mulch's national promo (store_id IS NULL), rescuing ('2025-04-12', 20, 302, 3, 12.6).
Complexity
Let O, I, P, and R be the row counts of orders, order_items, products, and promotions, and let M be the number of delivered mulch lines inside the New York reporting window (M <= I).
- Time: Joining
orders,order_items, andproductstakesO(O + I + P)expected time using hash joins (building an in-memory key table onordersandproductsand probing once perorder_itemsrow), orO(I log O)with primary-key B-tree lookups. For each of theMcandidate mulch lines,EXISTScheckspromotions: with a composite index (an index sorted on multiple columns together) onpromotions(promo_name, product_id, start_date, end_date), each lookup inspects only the Spring Mulch Promo entries for that product rather than scanning allRrows (O(M * R)unindexed). Finally,GROUP BY l.order_date_et, l.store_id, l.product_idhashes or sorts the surviving lines inO(M)expected time (O(M log M)worst case). - Space: The query keeps hash tables for the filtered
orders/productskeys plus one accumulator per(order_date_et, store_id, product_id)output group (O(G)whereG <= M).
On a date-partitioned orders table, filtering only on the computed expression order_date_et prevents partition pruning (skipping storage partitions outside the target months) because order_ts_utc is wrapped inside DATE(...). Adding a slightly wider raw guard in order_lines — AND o.order_ts_utc >= '2025-03-01 00:00:00' AND o.order_ts_utc < '2025-06-02 00:00:00' — lets the engine prune irrelevant months on raw order_ts_utc while order_date_et BETWEEN '2025-03-01' AND '2025-05-31' still enforces the exact New York boundary!
Edge cases
- National promotions (
promotions.store_id IS NULL): Match every store (10,20, and30) viaOR pr.store_id IS NULL. - Store-specific promotions (
promotions.store_idpopulated): Match only orders placed at that exacto.store_id; the same product sold at another store (Order 2004, product301at Store20) is excluded unless a national promo also covers it. - Overlapping store and national promotions (or duplicate promo rows): Counted once per order line (as in Example 2) because
EXISTSstops at the first matching promo row. - Late-evening Eastern orders crossing UTC midnight: Dated according to
America/New_York(Order 2001at2025-03-05 03:30:00UTC becomes2025-03-04EST,Order 2003at2025-04-16 02:15:00UTC becomes2025-04-15EDT, andOrder 2006at2025-06-01 02:45:00UTC becomes2025-05-31EDT). - Daylight Saving Time switch (
2025-03-09 07:00:00UTC): Timestamps before the switch use EST (-5 hours, so2025-03-05 03:30:00UTC is2025-03-04ET), while timestamps at or after07:00:00UTC use EDT (-4 hours, so2025-04-15 04:30:00UTC is2025-04-15ET). - Stores in non-Eastern timezones (
America/Chicago): Still dated inAmerica/New_Yorkper the requirement that reporting usesAmerica/New_Yorkas the business timezone. - Cancelled orders, non-mulch categories, and other promo names: Excluded cleanly.
Common mistakes
- Inner-joining
storesonpr.store_id = s.store_id: Drops every national promotion becauseNULL = store_idis neverTRUE. - Forgetting parentheses around
OR(AND pr.store_id = l.store_id OR pr.store_id IS NULL): BecauseANDhas higher precedence thanOR, omitting parentheses lets any national promotion active onorder_date_etmatch regardless ofproduct_idorpromo_name! - Using
DATE(o.order_ts_utc)without timezone conversion: Misassigns evening US orders to the next calendar day and drops final-night promotion sales. - Hardcoding a single UTC offset (
-4 hoursor-5 hours) across March:America/New_Yorkchanges fromUTC-5toUTC-4on March 9, 2025 right inside the2025-03-01 .. 2025-05-31window. - Joining
promotionsdirectly without deduplication: Double-counts quantity and revenue whenever both a regional/store promo and a national promo apply on the same day.
Follow-up questions
- How would you express the America/New_York timezone conversion in PostgreSQL, or generalize the SQLite offset across multiple calendar years? In PostgreSQL (or Snowflake/BigQuery/DuckDB), use the built-in IANA timezone database:
(o.order_ts_utc AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York')::date(or a singleAT TIME ZONE 'America/New_York'if the column type is alreadyTIMESTAMPTZ). In SQLite, you can encode the post-2007 US DST rule — second Sunday of March at07:00UTC until first Sunday of November at06:00UTC — using SQLite's'weekday 0'date modifier, which advances a date to the next Sunday (or stays put if it is already Sunday):
sql
DATE(
o.order_ts_utc,
CASE
WHEN o.order_ts_utc >= DATE(SUBSTR(o.order_ts_utc, 1, 4) || '-03-01', 'weekday 0', '+7 days') || ' 07:00:00'
AND o.order_ts_utc < DATE(SUBSTR(o.order_ts_utc, 1, 4) || '-11-01', 'weekday 0') || ' 06:00:00'
THEN '-4 hours'
ELSE '-5 hours'
END
) AS order_date_et
-
When should promotion eligibility use each store's local timezone rather than the company-wide America/New_York reporting timezone? Follow the stated requirement (
America/New_Yorkfor company-wide reporting), and flag the operational nuance proactively with your stakeholder! In brick-and-mortar retail, in-store price signage typically follows the store's local calendar day (a shopper checking out at23:30Central at Store30on April 10 expects an April 10 promo, even though headquarters clocks in New York already read00:30on April 11). If promo eligibility is store-local while finance reports in Eastern time,LEFT JOIN stores AS s ON s.store_id = o.store_id, evaluatepr.start_date .. pr.end_dateagainst(o.order_ts_utc AT TIME ZONE 'UTC' AT TIME ZONE COALESCE(s.timezone, 'America/New_York'))::date, and still group byorder_date_et. -
What automated data-quality assertions would you add upstream to prevent silent defects in promotions and orders? Add three automated assertions: (1) verify that
is_nationalagrees withstore_id IS NULLso upstream pipelines never insert contradictory flags, (2) flag overlapping same-product promotions so analysts who forgetEXISTSknow overlaps exist, and (3) check fororders.store_idvalues missing fromstores:
```sql -- 1. Flag contradictory national vs store_id rows SELECT promo_id, store_id, is_national FROM promotions WHERE (store_id IS NULL AND is_national = FALSE) OR (store_id IS NOT NULL AND is_national = TRUE);
-- 2. Flag overlapping promotions that can double-count naive joins SELECT a.promo_id, b.promo_id AS overlapping_promo_id FROM promotions AS a JOIN promotions AS b ON a.product_id = b.product_id AND a.promo_id < b.promo_id AND a.start_date <= b.end_date AND b.start_date <= a.end_date AND (a.store_id IS NULL OR b.store_id IS NULL OR a.store_id = b.store_id); ```
Follow-up questions
- How would you express the America/New_York timezone conversion in PostgreSQL, or generalize the SQLite offset across multiple calendar years?
- When should promotion eligibility use each store's local timezone rather than the company-wide America/New_York reporting timezone?
- What automated data-quality assertions would you add upstream to prevent silent defects in promotions and orders?
Similar questions
- Fixing Outer-Join Row Loss in Daily Mulch Sales
- 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