KatInterview

Multi-Task SQL Analytics for On-Demand Logistics

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionsgaps-and-islands

Last 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:

  1. 7-Day Conversion Rate (2025-08-26 to 2025-09-01 inclusive): For every combination of customer city (users.city) and courier_type, calculate:

    • Total created orders initiated within this window.
    • Total delivered orders (defined strictly as status = 'delivered' AND delivered_at IS NOT NULL).
    • Conversion rate (delivered_orders / created_orders), rounded to 4 decimal places. Avoid division by zero.
  2. Monthly Aggregate Scaffolding (2025-07 to 2025-09): Generate a monthly summary reporting month_label, courier_type, total orders created, total orders delivered, and total estimated GMV (calculated as delivered_orders * 10). Group orders by their created_at timestamp. Ensure every month-and-courier combination appears in the output, even if zero orders were created for that combination.

  3. 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.
  4. 95th Percentile Delivery Time: For all orders created in the last 30 days (2025-08-03 to 2025-09-01 inclusive) that reached status 'delivered' with a valid delivered_at, calculate the 95th percentile of fulfillment duration (in minutes) per courier_type. Include total delivered order counts per courier type.

  5. Full City × Month Scaffolding: Extend Task 2 to group by city, month_label, and courier_type. The target set of cities must be the distinct union of all cities present in users and couriers (users.city ∪ couriers.city). Ensure missing combinations are preserved with zero counts.

  6. Overdue / Stale Order Flagging: Identify orders created on or before 2025-09-01 00:00:00 that were not successfully delivered within 2 hours of creation (i.e., delivered_at is NULL or delivered_at > created_at + INTERVAL '2 hours'). Return order_id, user_id, courier_type, status, created_at, delivered_at, and a boolean column is_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.