KatInterview

Rolling Cold-Food Delivery Metric Calculation in PostgreSQL

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionsaggregations

Last updated

Write PostgreSQL queries to flag cold food deliveries, calculate daily and rolling 7-day cold delivery rates, rank restaurants, and detect courier quality outliers with z-scores.

You are analyzing delivery quality for a meal delivery company. A completed delivery is classified as a cold delivery if either of the following conditions is met:

  1. The recorded food temperature at dropoff (food_temp_c) is strictly below 40°C (food_temp_c < 40).
  2. A customer submits a complaint of type 'cold_food' within a 2-hour window following dropoff (created_ts is between dropoff_ts and dropoff_ts + INTERVAL '2 hours', inclusive).

Orders without a valid dropoff_ts in the delivery record are incomplete and must be excluded from all calculations. Assume today's date for reporting purposes is 2025-09-01 (making the target 7-day reporting period 2025-08-26 to 2025-09-01 inclusive).

Input Schema

orders

Column NameTypeDescription
order_idINTPrimary key
customer_idINTCustomer identifier
restaurant_idINTForeign key to restaurants
order_tsTIMESTAMPTimestamp when the order was placed

deliveries

Column NameTypeDescription
order_idINTForeign key to orders
courier_idINTCourier identifier
pickup_tsTIMESTAMPTimestamp when courier picked up order
dropoff_tsTIMESTAMPTimestamp when order was dropped off
food_temp_cINTMeasured food temperature in Celsius at dropoff
outside_temp_cINTAmbient temperature in Celsius

complaints

Column NameTypeDescription
order_idINTForeign key to orders
created_tsTIMESTAMPTimestamp when complaint was submitted
typeTEXTComplaint category (e.g., 'cold_food', 'wrong_item')
sourceTEXTReporting channel (e.g., 'app', 'web')

restaurants

Column NameTypeDescription
restaurant_idINTPrimary key
nameTEXTRestaurant name
cityTEXTCity name

Tasks

Write PostgreSQL queries for the following requirements:

  1. Daily Summary: For each calendar day in the 7-day period (2025-08-26 to 2025-09-01), calculate delivered_orders, cold_deliveries, and cold_rate (rounded to 3 decimal places). An order meeting both cold criteria must be counted exactly once. Ensure days with zero completed deliveries appear with 0 delivered orders and a NULL cold rate.
  2. Restaurant 7-Day Rolling Rate: For every restaurant, compute a 7-day rolling cold rate for each date from 2025-08-26 to 2025-09-01. Return date, restaurant_id, delivered_orders (on that date), cold_deliveries (on that date), and rolling_cold_rate_7d (rounded to 3 decimal places). The rolling rate must reflect the sum of cold deliveries divided by total deliveries over the 7-day window ending on that date.
  3. Restaurant Leaderboard: Using the 7-day rolling figures on 2025-09-01, rank restaurants by their 7-day cold rate in descending order using DENSE_RANK(). Break ties by prioritizing higher total 7-day delivered order volume (delivered_orders_7d DESC). Return the top 3 restaurants with columns: restaurant_id, name, delivered_orders_7d, cold_rate_7d, and rank.
  4. Courier Outlier Detection: Calculate each courier's overall cold delivery rate over the 7-day window (2025-08-26 to 2025-09-01). Then compute the population mean and population standard deviation across all active couriers in that period. Return couriers whose cold rate standard score (z-score) exceeds +2.0. Output: courier_id, deliveries_7d, cold_rate_7d, and z_score (rounded to 3 decimal places).

Constraints & Edge Cases

  • Duplicate Complaints: A customer may submit multiple complaints for a single order. A delivery must be flagged as cold at most once per order.
  • Null Temperatures: A missing (NULL) food_temp_c value should not cause a failure; the system must rely on the complaint window check.
  • Missing Delivery Records: orders rows without matching deliveries or with dropoff_ts IS NULL must be omitted.
  • Date Boundary Safety: Attribute orders based on dropoff_ts::date. When filtering date boundaries, use half-open range queries (e.g., >= '2025-08-26' AND < '2025-09-02') to ensure midnight dropoffs are safely captured.

Hints

Hint 1

Pre-aggregate complaints or use an EXISTS subquery within a CTE to avoid duplicating order rows when joining multi-complaint orders.

Hint 2

To calculate true 7-day rolling windows across sparse data, generate a complete Cartesian product (spine) of entities (restaurants) and dates before applying window functions over ROWS BETWEEN 6 PRECEDING AND CURRENT ROW.

Hint 3

Calculate rolling rates as SUM(cold) / SUM(total) over the window rather than taking the average of daily ratios.