Rolling Cold-Food Delivery Metric Calculation in PostgreSQL
SQL & DataModel answerLast 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:
- The recorded food temperature at dropoff (
food_temp_c) is strictly below 40°C (food_temp_c < 40). - A customer submits a complaint of type
'cold_food'within a 2-hour window following dropoff (created_tsis betweendropoff_tsanddropoff_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 Name | Type | Description |
|---|---|---|
order_id | INT | Primary key |
customer_id | INT | Customer identifier |
restaurant_id | INT | Foreign key to restaurants |
order_ts | TIMESTAMP | Timestamp when the order was placed |
deliveries
| Column Name | Type | Description |
|---|---|---|
order_id | INT | Foreign key to orders |
courier_id | INT | Courier identifier |
pickup_ts | TIMESTAMP | Timestamp when courier picked up order |
dropoff_ts | TIMESTAMP | Timestamp when order was dropped off |
food_temp_c | INT | Measured food temperature in Celsius at dropoff |
outside_temp_c | INT | Ambient temperature in Celsius |
complaints
| Column Name | Type | Description |
|---|---|---|
order_id | INT | Foreign key to orders |
created_ts | TIMESTAMP | Timestamp when complaint was submitted |
type | TEXT | Complaint category (e.g., 'cold_food', 'wrong_item') |
source | TEXT | Reporting channel (e.g., 'app', 'web') |
restaurants
| Column Name | Type | Description |
|---|---|---|
restaurant_id | INT | Primary key |
name | TEXT | Restaurant name |
city | TEXT | City name |
Tasks
Write PostgreSQL queries for the following requirements:
- Daily Summary: For each calendar day in the 7-day period (
2025-08-26to2025-09-01), calculatedelivered_orders,cold_deliveries, andcold_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 aNULLcold rate. - Restaurant 7-Day Rolling Rate: For every restaurant, compute a 7-day rolling cold rate for each date from
2025-08-26to2025-09-01. Returndate,restaurant_id,delivered_orders(on that date),cold_deliveries(on that date), androlling_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. - Restaurant Leaderboard: Using the 7-day rolling figures on
2025-09-01, rank restaurants by their 7-day cold rate in descending order usingDENSE_RANK(). Break ties by prioritizing higher total 7-day delivered order volume (delivered_orders_7dDESC). Return the top 3 restaurants with columns:restaurant_id,name,delivered_orders_7d,cold_rate_7d, andrank. - Courier Outlier Detection: Calculate each courier's overall cold delivery rate over the 7-day window (
2025-08-26to2025-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, andz_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_cvalue should not cause a failure; the system must rely on the complaint window check. - Missing Delivery Records:
ordersrows without matchingdeliveriesor withdropoff_ts IS NULLmust 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Architecture
To solve all four tasks cleanly and avoid common pitfalls (such as fan-out from multiple complaints per order or missing dates), we structure the data using Common Table Expressions (CTEs):
-
Fact Normalization (
delivered&flagged):- Filter out incomplete deliveries (
dropoff_ts IS NULL). - Determine whether a delivery is "cold" using
EXISTSon thecomplaintstable rather than a standardLEFT JOIN. This guarantees that multiple complaints for a single order do not multiply rows in our underlying dataset. - For rolling calculations covering 2025-08-26 through 2025-09-01, pull data starting 6 days prior (from
2025-08-20) so that window functions on 2025-08-26 have a full 7-day history.
- Filter out incomplete deliveries (
-
Date & Restaurant Spines:
- Use
generate_seriesto create complete date ranges. - For restaurant calculations,
CROSS JOINrestaurants with the date series to form a full grid. This ensures days with 0 volume are retained, preventing window functions (ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) from accidentally skipping days and aggregating non-adjacent calendar dates.
- Use
Shared Base CTEs
WITH delivered AS (
SELECT
o.order_id,
o.restaurant_id,
d.courier_id,
d.dropoff_ts,
d.dropoff_ts::date AS dropoff_date,
d.food_temp_c
FROM orders o
JOIN deliveries d ON o.order_id = d.order_id
WHERE d.dropoff_ts IS NOT NULL
AND d.dropoff_ts >= DATE '2025-08-20'
AND d.dropoff_ts < DATE '2025-09-02'
),
flagged AS (
SELECT
d.*,
(
COALESCE(d.food_temp_c < 40, FALSE)
OR EXISTS (
SELECT 1
FROM complaints c
WHERE c.order_id = d.order_id
AND c.type = 'cold_food'
AND c.created_ts >= d.dropoff_ts
AND c.created_ts <= d.dropoff_ts + INTERVAL '2 hours'
)
) AS is_cold
FROM delivered d
)
Task 1: Daily Summary
WITH delivered AS (...), flagged AS (...)
, days AS (
SELECT g::date AS dt
FROM generate_series(DATE '2025-08-26', DATE '2025-09-01', INTERVAL '1 day') g
),
daily_summary AS (
SELECT
d.dt,
COUNT(f.order_id) AS delivered_orders,
COUNT(f.order_id) FILTER (WHERE f.is_cold) AS cold_deliveries
FROM days d
LEFT JOIN flagged f ON f.dropoff_date = d.dt
GROUP BY d.dt
)
SELECT
dt AS date,
delivered_orders,
cold_deliveries,
ROUND(cold_deliveries::numeric / NULLIF(delivered_orders, 0), 3) AS cold_rate
FROM daily_summary
ORDER BY date;
Task 2: Per-Restaurant 7-Day Rolling Rate
WITH delivered AS (...), flagged AS (...)
, restaurant_spine AS (
SELECT
r.restaurant_id,
g::date AS dt
FROM restaurants r
CROSS JOIN generate_series(DATE '2025-08-20', DATE '2025-09-01', INTERVAL '1 day') g
),
daily_restaurant_aggregates AS (
SELECT
s.dt,
s.restaurant_id,
COUNT(f.order_id) AS delivered_orders,
COUNT(f.order_id) FILTER (WHERE f.is_cold) AS cold_deliveries
FROM restaurant_spine s
LEFT JOIN flagged f
ON f.restaurant_id = s.restaurant_id
AND f.dropoff_date = s.dt
GROUP BY s.dt, s.restaurant_id
),
rolling_metrics AS (
SELECT
dt,
restaurant_id,
delivered_orders,
cold_deliveries,
SUM(delivered_orders) OVER w AS delivered_7d,
SUM(cold_deliveries) OVER w AS cold_7d
FROM daily_restaurant_aggregates
WINDOW w AS (
PARTITION BY restaurant_id
ORDER BY dt
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
)
)
SELECT
dt AS date,
restaurant_id,
delivered_orders,
cold_deliveries,
ROUND(cold_7d::numeric / NULLIF(delivered_7d, 0), 3) AS rolling_cold_rate_7d
FROM rolling_metrics
WHERE dt BETWEEN DATE '2025-08-26' AND DATE '2025-09-01'
ORDER BY restaurant_id, date;
Task 3: Restaurant Leaderboard on 2025-09-01
WITH delivered AS (...), flagged AS (...)
, restaurant_7d AS (
SELECT
f.restaurant_id,
COUNT(f.order_id) AS delivered_orders_7d,
COUNT(f.order_id) FILTER (WHERE f.is_cold) AS cold_deliveries_7d
FROM flagged f
WHERE f.dropoff_date BETWEEN DATE '2025-08-26' AND DATE '2025-09-01'
GROUP BY f.restaurant_id
),
ranked_restaurants AS (
SELECT
r.restaurant_id,
r.name,
COALESCE(r7.delivered_orders_7d, 0) AS delivered_orders_7d,
ROUND(
COALESCE(r7.cold_deliveries_7d, 0)::numeric /
NULLIF(COALESCE(r7.delivered_orders_7d, 0), 0),
3
) AS cold_rate_7d,
DENSE_RANK() OVER (
ORDER BY
(COALESCE(r7.cold_deliveries_7d, 0)::numeric / NULLIF(COALESCE(r7.delivered_orders_7d, 0), 0)) DESC NULLS LAST,
COALESCE(r7.delivered_orders_7d, 0) DESC
) AS rank
FROM restaurants r
LEFT JOIN restaurant_7d r7 ON r.restaurant_id = r7.restaurant_id
)
SELECT restaurant_id, name, delivered_orders_7d, cold_rate_7d, rank
FROM ranked_restaurants
WHERE rank <= 3
ORDER BY rank, delivered_orders_7d DESC;
Task 4: Courier Outlier Detection (Z-Score > +2.0)
WITH delivered AS (...), flagged AS (...)
, courier_stats AS (
SELECT
courier_id,
COUNT(order_id) AS deliveries_7d,
COUNT(order_id) FILTER (WHERE is_cold) AS cold_deliveries_7d,
COUNT(order_id) FILTER (WHERE is_cold)::numeric / COUNT(order_id) AS cold_rate_7d
FROM flagged
WHERE dropoff_date BETWEEN DATE '2025-08-26' AND DATE '2025-09-01'
GROUP BY courier_id
),
courier_z_scores AS (
SELECT
courier_id,
deliveries_7d,
ROUND(cold_rate_7d, 3) AS cold_rate_7d,
ROUND(
(cold_rate_7d - AVG(cold_rate_7d) OVER ()) /
NULLIF(STDDEV_POP(cold_rate_7d) OVER (), 0),
3
) AS z_score
FROM courier_stats
)
SELECT courier_id, deliveries_7d, cold_rate_7d, z_score
FROM courier_z_scores
WHERE z_score > 2.0
ORDER BY z_score DESC;
Complexity & Design Considerations
- Time Complexity:
- Filtering base orders and deliveries takes $O(N)$ time, where $N$ is the number of delivery records.
- The
EXISTScheck evaluates indexed complaints in $O(N \log M)$ time ($M$ complaints). - Dense grid creation and window aggregate operations run in $O(R \cdot D \log D)$, where $R$ is the number of restaurants and $D$ is the number of days in the evaluation window.
- Space Complexity: $O(R \cdot D)$ temporary rows stored in memory for the dense window grid.
- Common Mistakes Avoided:
- Double counting:
EXISTSprevents row duplication when an order receives multiple complaints. - Window gaps: Generating a full date grid (
restaurants CROSS JOIN generate_series) preventsROWS BETWEEN 6 PRECEDING AND CURRENT ROWfrom shifting when a restaurant has days with no orders. - Averaged ratios: Windowed rates sum total numerator and denominator across the period (
SUM(cold) / SUM(total)) rather than computingAVG(daily_rate).
- Double counting: