Multi-Task SQL Analytics for On-Demand Logistics
SQL & DataModel answerLast updated
Solve multi-part SQL analytics queries covering sparse dimensions, gap-and-island sequences, conversion metrics, and latency percentiles.
You are analyzing order activity for an on-demand delivery platform. Assume a PostgreSQL-compatible SQL dialect and treat the reference date ("today") as 2025-09-01.
Database Schema
users:user_id(INT),signup_date(DATE),city(TEXT)orders:order_id(INT),user_id(INT),created_at(TIMESTAMP),delivered_at(TIMESTAMP, NULLABLE),courier_id(INT),distance_km(NUMERIC(5,1)),status(TEXT:'created','in_progress','delivered','cancelled'),courier_type(TEXT:'biker','car')couriers:courier_id(INT),type(TEXT:'biker','car'),start_date(DATE),city(TEXT)calendar_months:month_start(DATE, first day of month),month_label(TEXT)
Tasks
Write performant SQL queries for each of the following six analytics requirements:
-
7-Day Conversion Rate (
2025-08-26to2025-09-01inclusive): For every combination of customer city (users.city) andcourier_type, calculate:- Total created orders initiated within this window.
- Total delivered orders (defined strictly as
status = 'delivered'ANDdelivered_at IS NOT NULL). - Conversion rate (
delivered_orders / created_orders), rounded to 4 decimal places. Avoid division by zero.
-
Monthly Aggregate Scaffolding (
2025-07to2025-09): Generate a monthly summary reportingmonth_label,courier_type, total orders created, total orders delivered, and total estimated GMV (calculated asdelivered_orders * 10). Group orders by theircreated_attimestamp. Ensure every month-and-courier combination appears in the output, even if zero orders were created for that combination. -
Consecutive Biker Streak Detection: For each customer, find the first occurrence where they achieved a streak of 3 consecutive delivered orders fulfilled by a
'biker'.- Ignore non-delivered orders when building the sequence.
- Any non-biker delivery (
'car') breaks the streak. - Return
user_id,first_order_id,third_order_id, and the elapsed time in minutes between the creation timestamps of the first and third orders. - Exclude users who have never achieved such a streak.
-
95th Percentile Delivery Time: For all orders created in the last 30 days (
2025-08-03to2025-09-01inclusive) that reached status'delivered'with a validdelivered_at, calculate the 95th percentile of fulfillment duration (in minutes) percourier_type. Include total delivered order counts per courier type. -
Full City × Month Scaffolding: Extend Task 2 to group by
city,month_label, andcourier_type. The target set of cities must be the distinct union of all cities present inusersandcouriers(users.city ∪ couriers.city). Ensure missing combinations are preserved with zero counts. -
Overdue / Stale Order Flagging: Identify orders created on or before
2025-09-01 00:00:00that were not successfully delivered within 2 hours of creation (i.e.,delivered_atis NULL ordelivered_at > created_at + INTERVAL '2 hours'). Returnorder_id,user_id,courier_type,status,created_at,delivered_at, and a boolean columnis_stale_2h.
Hints
Hint 1
For date range filtering on timestamps, use half-open intervals (`created_at >= '2025-08-26' AND created_at < '2025-09-02'`) to prevent omitting events on the final day past midnight.
Hint 2
To retain zero-count periods across categorical dimensions, CROSS JOIN your dimension tables (or inline values) to construct a grid scaffold before LEFT JOINing aggregated facts.
Hint 3
For sequential pattern queries (gaps-and-islands / streaks), filter out irrelevant states first, then leverage `LEAD()` over a ordered window grouped by entity.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Key Analytical Principles & Assumptions
- City Attribution: Orders inherit the user's city (
users.city) unless stated otherwise. - Definition of Delivered: An order is deemed successfully delivered if and only if
status = 'delivered' AND delivered_at IS NOT NULL. - Date Filtering Syntax: Timestamp filters use half-open intervals (e.g.,
>= '2025-08-26' AND < '2025-09-02') so that records occurring at any point on2025-09-01are correctly included while remaining index-friendly. - Zero-Safe Division: Use
NULLIF(..., 0)to avoid runtime division-by-zero errors.
Part A: 7-Day Conversion Rate
SELECT
u.city,
o.courier_type,
COUNT(*) AS created_orders,
COUNT(*) FILTER (
WHERE o.status = 'delivered' AND o.delivered_at IS NOT NULL
) AS delivered_orders,
ROUND(
COUNT(*) FILTER (
WHERE o.status = 'delivered' AND o.delivered_at IS NOT NULL
)::NUMERIC / NULLIF(COUNT(*), 0),
4
) AS conversion
FROM orders o
JOIN users u ON u.user_id = o.user_id
WHERE o.created_at >= DATE '2025-08-26'
AND o.created_at < DATE '2025-09-02'
GROUP BY u.city, o.courier_type
ORDER BY u.city, o.courier_type;
Part B: Monthly Volume with Complete Dimensional Grid
WITH monthly_summary AS (
SELECT
DATE_TRUNC('month', created_at)::DATE AS month_start,
courier_type,
COUNT(*) AS orders_created,
COUNT(*) FILTER (
WHERE status = 'delivered' AND delivered_at IS NOT NULL
) AS orders_delivered
FROM orders
WHERE created_at >= DATE '2025-07-01'
AND created_at < DATE '2025-10-01'
GROUP BY 1, 2
),
grid AS (
SELECT
cm.month_start,
cm.month_label,
t.courier_type
FROM calendar_months cm
CROSS JOIN (VALUES ('biker'), ('car')) AS t(courier_type)
WHERE cm.month_start BETWEEN DATE '2025-07-01' AND DATE '2025-09-01'
)
SELECT
g.month_label,
g.courier_type,
COALESCE(m.orders_created, 0) AS orders_created,
COALESCE(m.orders_delivered, 0) AS orders_delivered,
COALESCE(m.orders_delivered, 0) * 10 AS gmv
FROM grid g
LEFT JOIN monthly_summary m
ON m.month_start = g.month_start
AND m.courier_type = g.courier_type
ORDER BY g.month_label, g.courier_type;
Part C: Consecutive Biker Streaks
Filter down to delivered orders first, then apply LEAD() functions to inspect the next two consecutive delivered orders per user.
WITH delivered_orders AS (
SELECT
user_id,
order_id,
created_at,
courier_type
FROM orders
WHERE status = 'delivered'
AND delivered_at IS NOT NULL
),
sequenced_orders AS (
SELECT
d.*,
LEAD(courier_type, 1) OVER w AS next_type_1,
LEAD(courier_type, 2) OVER w AS next_type_2,
LEAD(order_id, 2) OVER w AS third_order_id,
LEAD(created_at, 2) OVER w AS third_created_at
FROM delivered_orders d
WINDOW w AS (PARTITION BY user_id ORDER BY created_at, order_id)
),
streak_starts AS (
SELECT
s.*,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at, order_id) AS streak_rank
FROM sequenced_orders s
WHERE courier_type = 'biker'
AND next_type_1 = 'biker'
AND next_type_2 = 'biker'
)
SELECT
user_id,
order_id AS first_order_id,
third_order_id,
EXTRACT(EPOCH FROM (third_created_at - created_at)) / 60.0 AS minutes_between
FROM streak_starts
WHERE streak_rank = 1;
Part D: p95 Delivery Duration
We use PERCENTILE_CONT(0.95) (continuous percentile interpolation) over the delivery duration in minutes.
SELECT
courier_type,
COUNT(*) AS delivered_orders,
PERCENTILE_CONT(0.95) WITHIN GROUP (
ORDER BY EXTRACT(EPOCH FROM (delivered_at - created_at)) / 60.0
) AS p95_delivery_minutes
FROM orders
WHERE status = 'delivered'
AND delivered_at IS NOT NULL
AND delivered_at >= created_at
AND created_at >= DATE '2025-08-03'
AND created_at < DATE '2025-09-02'
GROUP BY courier_type;
Part E: Multi-Dimensional City × Month Grid
WITH distinct_cities AS (
SELECT city FROM users WHERE city IS NOT NULL
UNION
SELECT city FROM couriers WHERE city IS NOT NULL
),
full_grid AS (
SELECT
c.city,
cm.month_start,
cm.month_label,
t.courier_type
FROM distinct_cities c
CROSS JOIN calendar_months cm
CROSS JOIN (VALUES ('biker'), ('car')) AS t(courier_type)
WHERE cm.month_start BETWEEN DATE '2025-07-01' AND DATE '2025-09-01'
),
monthly_facts AS (
SELECT
u.city,
DATE_TRUNC('month', o.created_at)::DATE AS month_start,
o.courier_type,
COUNT(*) AS orders_created,
COUNT(*) FILTER (
WHERE o.status = 'delivered' AND o.delivered_at IS NOT NULL
) AS orders_delivered
FROM orders o
JOIN users u ON u.user_id = o.user_id
WHERE o.created_at >= DATE '2025-07-01'
AND o.created_at < DATE '2025-10-01'
GROUP BY 1, 2, 3
)
SELECT
g.city,
g.month_label,
g.courier_type,
COALESCE(m.orders_created, 0) AS orders_created,
COALESCE(m.orders_delivered, 0) AS orders_delivered,
COALESCE(m.orders_delivered, 0) * 10 AS gmv
FROM full_grid g
LEFT JOIN monthly_facts m
ON m.city = g.city
AND m.month_start = g.month_start
AND m.courier_type = g.courier_type
ORDER BY g.city, g.month_label, g.courier_type;
Part F: Aging / Overdue Undelivered Orders
SELECT
order_id,
user_id,
courier_type,
status,
created_at,
delivered_at,
(delivered_at IS NULL OR delivered_at > created_at + INTERVAL '2 hours') AS is_stale_2h
FROM orders
WHERE created_at <= TIMESTAMP '2025-09-01 00:00:00'
AND (delivered_at IS NULL OR delivered_at > created_at + INTERVAL '2 hours');