Multi-Part SQL Challenge on a Food Delivery Schema
SQL & DataModel answerLast updated
Write six targeted SQL queries spanning window functions, event anomalies, time-based filtering, and promo uplift analysis on a realistic food delivery dataset.
Setting the Scene
You are working with a food delivery platform's analytics database (BigQuery dialect). All timestamps are UTC. Set today = 2025-09-01 for any relative date calculations.
Use the schema and sample data below to write precise SQL for tasks (a)–(f). Before each query, state any assumptions you are making about definitions, null handling, or time boundaries.
Schema & Sample Data
customers
| customer_id | signup_date | city |
|---|---|---|
| 1 | 2025-07-10 | SF |
| 2 | 2025-08-01 | SF |
| 3 | 2025-08-20 | NYC |
merchants
| merchant_id | name | city | cuisine |
|---|---|---|---|
| 10 | SushiCo | SF | Japanese |
| 11 | TacoTown | SF | Mexican |
| 12 | PizzaBox | NYC | Italian |
dashers
| dasher_id | signup_date | vehicle_type |
|---|---|---|
| 100 | 2025-06-01 | car |
| 101 | 2025-08-15 | bike |
promotions
| promo_id | promo_type | discount_amount | start_date | end_date |
|---|---|---|---|---|
| 900 | pct10 | 10.00 | 2025-08-01 | 2025-08-31 |
| 901 | flat5 | 5.00 | 2025-08-10 | 2025-09-10 |
orders
| order_id | customer_id | merchant_id | dasher_id | created_at | accepted_at | picked_up_at | delivered_at | canceled_at | subtotal | delivery_fee | tip_amount | promo_id | status |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 5001 | 1 | 10 | 100 | 2025-08-28 12:00 | 2025-08-28 12:02 | 2025-08-28 12:20 | 2025-08-28 12:35 | null | 30.00 | 3.99 | 5.00 | 900 | delivered |
| 5002 | 2 | 11 | null | 2025-08-29 18:05 | null | null | null | 2025-08-29 18:10 | 15.00 | 2.99 | 0.00 | null | canceled |
| 5003 | 1 | 11 | 101 | 2025-08-31 19:00 | 2025-08-31 19:04 | 2025-08-31 19:20 | null | null | 20.00 | 2.99 | 3.00 | 901 | in_progress |
| 5004 | 3 | 12 | 100 | 2025-08-24 11:30 | 2025-08-24 11:31 | null | 2025-08-24 12:10 | null | 22.00 | 4.99 | 0.00 | null | delivered |
order_events
| order_id | event_time | event_type |
|---|---|---|
| 5001 | 2025-08-28 12:00 | created |
| 5001 | 2025-08-28 12:02 | accepted |
| 5001 | 2025-08-28 12:20 | picked_up |
| 5001 | 2025-08-28 12:35 | delivered |
| 5002 | 2025-08-29 18:05 | created |
| 5002 | 2025-08-29 18:10 | canceled |
| 5003 | 2025-08-31 19:00 | created |
| 5003 | 2025-08-31 19:04 | accepted |
| 5004 | 2025-08-24 11:30 | created |
| 5004 | 2025-08-24 11:31 | accepted |
| 5004 | 2025-08-24 12:10 | delivered |
Tasks
(a) Compute the daily on-time delivery rate broken out by city for the period 2025-08-26 through 2025-09-01 (inclusive). Define on-time as delivered_at <= created_at + 45 minutes, applied only to non-canceled orders. A NULL delivered_at counts as late. Return city, date, on_time_deliveries, total_eligible, on_time_rate.
(b) For August 2025, rank the top 3 merchants per city by GMV, where GMV = subtotal + delivery_fee + tip_amount − COALESCE(discount_amount, 0). Exclude canceled orders from GMV but keep them for the cancellation tie-breaker. Break ties by fewest cancellations, then by lower merchant_id. Return city, merchant_id, rank_in_city, gmv, cancellations.
(c) Using order_events, identify orders that have a delivered event but no picked_up event that occurs strictly before it. Return order_id and a condensed event timeline up to and including the first delivery, as evidence of the anomaly.
(d) For each dasher and ISO calendar week, compute the acceptance rate: the share of dasher-assigned orders where accepted_at falls within 3 minutes of created_at. Exclude orders that were canceled before they were accepted. Return dasher_id, week_start_date, assigned_orders, accepted_within_3m, acceptance_rate.
(e) Find customers whose entire order history consists of exactly two orders, both of which were canceled. Return customer_id along with the two canceled_at timestamps in ascending order.
(f) For each merchant in August 2025 (non-canceled orders only), estimate the average order value (AOV) for promo orders versus non-promo orders. Return merchant_id, promo_orders, non_promo_orders, aov_promo, aov_nonpromo, diff. Then briefly describe how you would construct a 95% confidence interval for diff using either a SQL-based approximation or a short Python snippet.
Hints
Hint 1
For (a), use a half-open timestamp range (>= 2025-08-26, < 2025-09-02) so the full day of Sep 1 is included, and let COUNTIF handle the on-time boolean — NULL delivered_at naturally fails the <= condition, so it counts as late without extra logic.
Hint 2
For (b), put the cancellation count inside the CTE alongside GMV rather than filtering canceled rows out in the WHERE clause — you need them to compute the tie-breaker. Then apply ROW_NUMBER with the three-part ORDER BY (gmv DESC, cancellations ASC, merchant_id ASC) so ranks are always unique, and use QUALIFY to keep only the top 3.
Hint 3
For (c), aggregate order_events once to get the earliest delivered and earliest picked_up timestamps per order, then flag rows where first_pickup IS NULL or first_pickup >= first_delivered — both are anomalies because 'strictly earlier' is required. Build the timeline with STRING_AGG ordered by event_time, capped at the first delivery.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Global Assumptions
State these before touching the keyboard:
- Date scoping uses
created_atas the anchor column, expressed as half-open UTC ranges (>= start AND < exclusive_end). - City refers to the merchant's city (the delivery market), not the customer's.
- Canceled means
status = 'canceled';canceled_atis the timestamp of that event. promotions.discount_amountis the amount actually deducted, as stated in the schema note.
(a) Daily On-Time Delivery Rate by City
The 7-day window runs 2025-08-26 through 2025-09-01 inclusive, so the exclusive upper bound is 2025-09-02.
SELECT
m.city,
DATE(o.created_at) AS date,
COUNTIF(
o.delivered_at IS NOT NULL
AND o.delivered_at <= TIMESTAMP_ADD(o.created_at, INTERVAL 45 MINUTE)
) AS on_time_deliveries,
COUNT(*) AS total_eligible,
SAFE_DIVIDE(
COUNTIF(
o.delivered_at IS NOT NULL
AND o.delivered_at <= TIMESTAMP_ADD(o.created_at, INTERVAL 45 MINUTE)
),
COUNT(*)
) AS on_time_rate
FROM orders o
JOIN merchants m USING (merchant_id)
WHERE o.created_at >= TIMESTAMP '2025-08-26'
AND o.created_at < TIMESTAMP '2025-09-02'
AND o.status != 'canceled'
GROUP BY city, date
ORDER BY city, date;
Key decisions:
- A NULL
delivered_atfails the<=check naturally — noCOALESCEneeded. SAFE_DIVIDEreturns NULL instead of a division-by-zero error on empty days.- Order 5003 (in progress, NULL
delivered_at) is correctly treated as late. - In production you would exclude orders younger than 45 minutes that haven't been delivered yet, since they are still in flight and cannot be judged.
Sample result: SF on 2025-08-28 → 1/1 = 1.0. SF on 2025-08-31 → 0/1 = 0.0. Order 5004 is outside the window.
(b) Top 3 Merchants per City by August GMV
WITH merchant_stats AS (
SELECT
m.city,
o.merchant_id,
SUM(
CASE WHEN o.status != 'canceled'
THEN o.subtotal + o.delivery_fee + o.tip_amount
- COALESCE(p.discount_amount, 0)
ELSE 0
END
) AS gmv,
COUNTIF(o.status = 'canceled') AS cancellations
FROM orders o
JOIN merchants m USING (merchant_id)
LEFT JOIN promotions p USING (promo_id)
WHERE o.created_at >= TIMESTAMP '2025-08-01'
AND o.created_at < TIMESTAMP '2025-09-01'
GROUP BY m.city, o.merchant_id
)
SELECT
city,
merchant_id,
ROW_NUMBER() OVER (
PARTITION BY city
ORDER BY gmv DESC, cancellations ASC, merchant_id ASC
) AS rank_in_city,
gmv,
cancellations
FROM merchant_stats
QUALIFY rank_in_city <= 3
ORDER BY city, rank_in_city;
Key decisions:
- Canceled orders stay in scope so their contribution to
cancellationsis counted for the tie-breaker. GMV contribution is zeroed out withCASE WHEN. LEFT JOIN promotionskeeps orders with no promo (a promo-less order would be dropped with an INNER JOIN).ROW_NUMBER(notRANK) guarantees unique ranks because the final tie-breaker ismerchant_id.
Sample result: SF: SushiCo GMV = 30 + 3.99 + 5 − 10 = 28.99 (rank 1). TacoTown GMV = 20 + 2.99 + 3 − 5 = 20.99, with 1 cancellation (rank 2). NYC: PizzaBox = 22 + 4.99 + 0 − 0 = 26.99 (rank 1).
(c) Delivered Without a Preceding Pickup Event
WITH order_anchors AS (
SELECT
order_id,
MIN(IF(event_type = 'delivered', event_time, NULL)) AS first_delivered,
MIN(IF(event_type = 'picked_up', event_time, NULL)) AS first_pickup
FROM order_events
GROUP BY order_id
)
SELECT
a.order_id,
STRING_AGG(
FORMAT('%t %s', e.event_time, e.event_type),
' -> '
ORDER BY e.event_time, e.event_type
) AS event_timeline
FROM order_anchors a
JOIN order_events e USING (order_id)
WHERE a.first_delivered IS NOT NULL
AND (a.first_pickup IS NULL OR a.first_pickup >= a.first_delivered)
AND e.event_time <= a.first_delivered
GROUP BY a.order_id;
Key decisions:
- Comparing the earliest pickup to the earliest delivery is sufficient: if any pickup precedes the first delivery, every later delivery also has a preceding pickup.
first_pickup >= first_deliveredcatches simultaneous events too, since the spec requires "strictly earlier."- The timeline is capped at
first_deliveredto provide minimal, focused evidence.
Sample result: Order 5004 → created -> accepted -> delivered (no picked_up row at all).
(d) Weekly Dasher Acceptance Rate
SELECT
dasher_id,
DATE_TRUNC(DATE(created_at), ISOWEEK) AS week_start_date,
COUNT(*) AS assigned_orders,
COUNTIF(
accepted_at IS NOT NULL
AND TIMESTAMP_DIFF(accepted_at, created_at, SECOND) BETWEEN 0 AND 180
) AS accepted_within_3m,
SAFE_DIVIDE(
COUNTIF(
accepted_at IS NOT NULL
AND TIMESTAMP_DIFF(accepted_at, created_at, SECOND) BETWEEN 0 AND 180
),
COUNT(*)
) AS acceptance_rate
FROM orders
WHERE dasher_id IS NOT NULL
AND NOT (
canceled_at IS NOT NULL
AND (accepted_at IS NULL OR canceled_at <= accepted_at)
)
GROUP BY dasher_id, week_start_date
ORDER BY dasher_id, week_start_date;
Key decisions:
DATE_TRUNC(..., ISOWEEK)anchors to the Monday of each week.- The exclusion filter removes any order where a cancel beat or tied the acceptance, including orders with no acceptance at all.
- A negative
TIMESTAMP_DIFFsignals a data quality issue and is excluded naturally byBETWEEN 0 AND 180. - Note:
dasher_idreflects the final assignee. A true per-offer acceptance rate would need a separate offer-dispatch log.
(e) Exactly Two Lifetime Orders, Both Canceled
SELECT
customer_id,
MIN(canceled_at) AS first_canceled_at,
MAX(canceled_at) AS second_canceled_at
FROM orders
GROUP BY customer_id
HAVING COUNT(*) = 2
AND COUNTIF(status = 'canceled' AND canceled_at IS NOT NULL) = 2;
Key decisions:
MINandMAXon two rows return the two timestamps in ascending order without any explicit sorting.- Checking both
status = 'canceled'andcanceled_at IS NOT NULLguards against rows where the status and the timestamp disagree.
Sample result: No rows — customer 2 has only one order.
(f) Promo vs. Non-Promo AOV per Merchant
AOV is computed on subtotal (basket size before fees), which best captures customer spend intent.
SELECT
merchant_id,
COUNTIF(promo_id IS NOT NULL) AS promo_orders,
COUNTIF(promo_id IS NULL) AS non_promo_orders,
AVG(IF(promo_id IS NOT NULL, subtotal, NULL)) AS aov_promo,
AVG(IF(promo_id IS NULL, subtotal, NULL)) AS aov_nonpromo,
AVG(IF(promo_id IS NOT NULL, subtotal, NULL))
- AVG(IF(promo_id IS NULL, subtotal, NULL)) AS diff
FROM orders
WHERE created_at >= TIMESTAMP '2025-08-01'
AND created_at < TIMESTAMP '2025-09-01'
AND status != 'canceled'
GROUP BY merchant_id;
AVG ignores NULLs automatically, so diff is NULL when either arm has no orders — which is the correct and honest result rather than a misleading zero.
95% CI for diff
SQL approach — Welch's approximation:
WITH arms AS (
SELECT
merchant_id,
IF(promo_id IS NOT NULL, 'promo', 'non_promo') AS arm,
AVG(subtotal) AS mean_val,
VAR_SAMP(subtotal) AS var_val,
COUNT(*) AS n
FROM orders
WHERE created_at >= TIMESTAMP '2025-08-01'
AND created_at < TIMESTAMP '2025-09-01'
AND status != 'canceled'
GROUP BY merchant_id, arm
)
SELECT
p.merchant_id,
p.mean_val - np.mean_val AS diff,
1.96 * SQRT(p.var_val / p.n + np.var_val / np.n) AS margin_of_error
FROM arms p
JOIN arms np USING (merchant_id)
WHERE p.arm = 'promo' AND np.arm = 'non_promo';
This is valid when n is large enough (roughly ≥ 30 per arm) for the CLT to apply.
Python bootstrap (for small samples):
import numpy as np
import pandas as pd
# df has columns: merchant_id, subtotal, promo_id
def bootstrap_ci(df, merchant_id, n_boot=10_000, alpha=0.05):
sub = df[df.merchant_id == merchant_id]
promo = sub[sub.promo_id.notna()]["subtotal"].values
non_promo = sub[sub.promo_id.isna()]["subtotal"].values
diffs = [
np.mean(np.random.choice(promo, len(promo), replace=True))
- np.mean(np.random.choice(non_promo, len(non_promo), replace=True))
for _ in range(n_boot)
]
lo, hi = np.percentile(diffs, [100 * alpha / 2, 100 * (1 - alpha / 2)])
return lo, hi
The bootstrap makes no distributional assumptions and is preferable for skewed order-value distributions or small samples. The SQL Welch approximation is faster to run inline but assumes approximate normality of the group means.
Common mistake to avoid: including discount_amount in the AOV numerator would conflate a promotion's mechanical price reduction with a genuine change in customer basket size, making the uplift estimate uninterpretable.