MediumAggregations
Fleet Route Delivery SLA Adherence
Frequently Asked By:AppleGoogleAmazon
Interactive In-Browser Workspace
Practice this problem on live schema tables in PostgreSQL 16 WASM with instant row verification and visual EXPLAIN plans.
Problem Statement
Group deliveries in `courier_deliveries` by `delivery_zone`.
Calculate:
1. `delivery_zone`
2. `total_packages`: Count of all deliveries
3. `avg_transit_minutes`: Average `transit_minutes` rounded to 1 decimal place
4. `on_time_pct`: Percentage of deliveries marked as on-time (`is_on_time = true`):
`ROUND(100.0 * SUM(CASE WHEN is_on_time THEN 1 ELSE 0 END) / COUNT(*), 1)`
Order results by `on_time_pct` ascending to see troubled zones first.
Why Technical Interviewers Ask This
QuickRide Logistics guarantees delivery windows across urban delivery zones. Regional fleet dispatchers need to audit delivery completion times and identify zones failing their 90% on-time target.
Common Pitfalls & Interview Traps
Forgetting required sorting and deterministic tie-breaking.
Not accounting for NULL or zero-value denominators during calculations.
Using inefficient quadratic subqueries instead of single-pass aggregations constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
delivery_zone,
COUNT(*) AS total_packages,
ROUND(AVG(transit_minutes), 1) AS avg_transit_minutes,
ROUND(100.0 * SUM(CASE WHEN is_on_time THEN 1 ELSE 0 END) / COUNT(*), 1) AS on_time_pct
FROM courier_deliveries
GROUP BY delivery_zone
ORDER BY on_time_pct ASC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Aggregations. It meets the target criteria: Delivery metrics per zone showing total packages, average transit time, and on-time percentage.Edge Cases to Verbally Clarify with Your Interviewer
The dataset contains zero matching records (must return valid empty result without crashing).
Multiple records tie on sorting criteria (must evaluate tie-breaking order deterministically).
Foreign keys or secondary attributes have NULL values.
Frequently Asked Follow-Up Questions
What makes this question a favorite among Apple and Google interviewers?
Interviewers use this problem to test whether candidates write defensive, scalable Aggregations queries that run efficiently on multi-million row production databases without excessive memory usage.
How does the query optimizer execute this query?
Using single-pass table scans with index lookups or sort buffers. Running EXPLAIN (ANALYZE, BUFFERS) in the DB Exercises workbench visualizes the execution nodes and buffer hit cache.