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-01 through 2025-05-31 inclusive, evaluated on the America/New_York calendar date (order_date_et).
  • Eligible orders & items: Include only orders with order_status = 'DELIVERED' and line items whose product has category = 'Mulch'.
  • Promotion coverage: A line item qualifies when at least one 'Spring Mulch Promo' row matches its product_id, covers order_date_et (start_date <= order_date_et <= end_date inclusive), 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) reporting units_sold = SUM(quantity) and gross_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:

  1. Explain why the join chain discards valid rows.
  2. Identify every join, grain, and timezone/date defect in the original query.
  3. Write the corrected SQL query assigned to QUERY returning order_date_et, store_id, product_id, units_sold, and gross_revenue in 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_utc timestamp to America/New_York (EST = UTC-5 prior to 2025-03-09 07:00:00 UTC; EDT = UTC-4 from 2025-03-09 07:00:00 UTC onward through the end of May 2025), regardless of stores.timezone.
  • Enforce order_date_et BETWEEN '2025-03-01' AND '2025-05-31' inclusive, order_status = 'DELIVERED', products.category = 'Mulch', and promotions.promo_name = 'Spring Mulch Promo'.
  • Match promotions where promotions.product_id = order_items.product_id, order_date_et BETWEEN start_date AND end_date inclusive, 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; round gross_revenue to 2 decimal places. Row order does not matter.

Step-by-step walkthrough

  1. 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) reporting units_sold = SUM(quantity) and gross_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 in 2025-03-01 .. 2025-05-31 inclusive.
    • At least one 'Spring Mulch Promo' row covers that product on order_date_et (start_date .. end_date inclusive) 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.
  2. Why the buggy query loses rows: the five bugs

    Trace the original FROM and WHERE clauses 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 lines
    
    1. JOIN stores s ON pr.store_id = s.store_id wipes out every national promotion (biggest row loss). National promotions store NULL in promotions.store_id. Because NULL = s.store_id evaluates to UNKNOWN (never TRUE), 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.
    2. store_id is routed through promotions instead of orders. Selecting s.store_id (joined to pr.store_id) and filtering o.store_id = s.store_id leaves no way for a NULL promo store to match every order store.
    3. DATE(o.order_ts_utc) uses UTC instead of America/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 at 22:15 EDT on April 15 (2025-04-16 02:15:00 UTC, Order 2003 in Example 1) gets dated 2025-04-16 in UTC — pushing it past an April 15 promo end_date and dropping it (while Order 2001 at 2025-03-05 03:30:00 UTC gets split onto 2025-03-05 instead of 2025-03-04 EST)!
    4. The 2025-03-01 .. 2025-05-31 analysis window is missing. If a 'Spring Mulch Promo' runs until June 15, June orders slip into the output.
    5. Joining promotions directly causes join fan-out. Whenever both a store promo and a national promo (as in Example 2) cover the same line, JOIN promotions emits two rows for one item and doubles units_sold and gross_revenue.

    On Example 1, these bugs lose all national promo orders, drop Order 2003, and misdate Order 2001 onto 2025-03-05.

  3. 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, and SUM(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 j6
    

    On 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!
    
  4. Convert UTC timestamps to New York calendar dates

    Every date check — the reporting column, the 2025-03-01 .. 2025-05-31 window, and the promotion start_date .. end_date check — must use the America/New_York calendar date, so compute order_date_et once 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) at 02:00 EST, which is 2025-03-09 07:00:00 UTC, 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-30
    

    Notice why a hardcoded '-4 hours' would misdate 2025-03-05 04:30:00 UTC as 2025-03-05 (00:30) instead of 2025-03-04 (23:30 EST)!

            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,
    
  5. Build one clean row per delivered mulch line

    In order_lines, join only orders, order_items, and products — primary-key joins that preserve exact one-row-per-order-line grain:

    • Take o.store_id directly from orders (where the order occurred).
    • Do not join stores at all: none of its columns appear in the output, and the business timezone is fixed to America/New_York for company-wide reporting (even for Store 30 in America/Chicago).
    • Filter o.order_status = 'DELIVERED' and p.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'
    )
    
  6. Match store-specific and national promotions with EXISTS

    Now filter order_lines to the 2025-03-01 .. 2025-05-31 New York window and check promotion coverage with EXISTS:

    • EXISTS asks 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, AND binds tighter than OR. Without parentheses, A AND B AND pr.store_id = l.store_id OR pr.store_id IS NULL AND D splits at OR, allowing any national promotion active on that date (even 'Memorial Patio Sale') to match!
    • Because l.order_date_et, pr.start_date, and pr.end_date are all DATE values without timestamps, BETWEEN pr.start_date AND pr.end_date includes 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_id
    
  7. Trace Example 1 row by row

    Orders 2001 and 2002 precede 2025-03-09 07:00:00 UTC so EST (-5 hours) applies, while Orders 2003..2006 use 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)
  8. 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, and products takes O(O + I + P) expected time using hash joins (building an in-memory key table on orders and products and probing once per order_items row), or O(I log O) with primary-key B-tree lookups. For each of the M candidate mulch lines, EXISTS checks promotions: with a composite index (an index sorted on multiple columns together) on promotions(promo_name, product_id, start_date, end_date), each lookup inspects only the Spring Mulch Promo entries for that product rather than scanning all R rows (O(M * R) unindexed). Finally, GROUP BY l.order_date_et, l.store_id, l.product_id hashes or sorts the surviving lines in O(M) expected time (O(M log M) worst case).
  • Space: The query keeps hash tables for the filtered orders/products keys plus one accumulator per (order_date_et, store_id, product_id) output group (O(G) where G <= 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, and 30) via OR pr.store_id IS NULL.
  • Store-specific promotions (promotions.store_id populated): Match only orders placed at that exact o.store_id; the same product sold at another store (Order 2004, product 301 at Store 20) 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 EXISTS stops at the first matching promo row.
  • Late-evening Eastern orders crossing UTC midnight: Dated according to America/New_York (Order 2001 at 2025-03-05 03:30:00 UTC becomes 2025-03-04 EST, Order 2003 at 2025-04-16 02:15:00 UTC becomes 2025-04-15 EDT, and Order 2006 at 2025-06-01 02:45:00 UTC becomes 2025-05-31 EDT).
  • Daylight Saving Time switch (2025-03-09 07:00:00 UTC): Timestamps before the switch use EST (-5 hours, so 2025-03-05 03:30:00 UTC is 2025-03-04 ET), while timestamps at or after 07:00:00 UTC use EDT (-4 hours, so 2025-04-15 04:30:00 UTC is 2025-04-15 ET).
  • Stores in non-Eastern timezones (America/Chicago): Still dated in America/New_York per the requirement that reporting uses America/New_York as the business timezone.
  • Cancelled orders, non-mulch categories, and other promo names: Excluded cleanly.

Common mistakes

  • Inner-joining stores on pr.store_id = s.store_id: Drops every national promotion because NULL = store_id is never TRUE.
  • Forgetting parentheses around OR (AND pr.store_id = l.store_id OR pr.store_id IS NULL): Because AND has higher precedence than OR, omitting parentheses lets any national promotion active on order_date_et match regardless of product_id or promo_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 hours or -5 hours) across March: America/New_York changes from UTC-5 to UTC-4 on March 9, 2025 right inside the 2025-03-01 .. 2025-05-31 window.
  • Joining promotions directly 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 single AT TIME ZONE 'America/New_York' if the column type is already TIMESTAMPTZ). In SQLite, you can encode the post-2007 US DST rule — second Sunday of March at 07:00 UTC until first Sunday of November at 06:00 UTC — 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_York for 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 at 23:30 Central at Store 30 on April 10 expects an April 10 promo, even though headquarters clocks in New York already read 00:30 on 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, evaluate pr.start_date .. pr.end_date against (o.order_ts_utc AT TIME ZONE 'UTC' AT TIME ZONE COALESCE(s.timezone, 'America/New_York'))::date, and still group by order_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_national agrees with store_id IS NULL so upstream pipelines never insert contradictory flags, (2) flag overlapping same-product promotions so analysts who forget EXISTS know overlaps exist, and (3) check for orders.store_id values missing from stores:

```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

Similar questions

More Home Depot interview questions

All 3 Home Depot questions →