HardCTEs High Frequency
Cumulative Route Leg Transit & Total Duration
Frequently Asked By:UberAmazonMeta
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
Write a query using a CTE to aggregate total transit time per delivery route in `route_stops`.
Calculate:
1. `route_id`
2. `stop_count`: Total number of stops on the route
3. `total_driving_minutes`: Sum of `leg_minutes`
4. `exceeds_shift_limit`: Boolean flag `CASE WHEN SUM(leg_minutes) > 480 THEN true ELSE false END`
Order results by `total_driving_minutes` descending.
Why Technical Interviewers Ask This
Regional freight dispatchers monitor multi-stop delivery routes to ensure drivers do not exceed mandatory regulatory driving shift limits of 480 minutes (8 hours).
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 ctes constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLWITH route_aggregates AS (
SELECT
route_id,
COUNT(*) AS stop_count,
SUM(leg_minutes) AS total_driving_minutes
FROM route_stops
GROUP BY route_id
)
SELECT
route_id,
stop_count,
total_driving_minutes,
CASE WHEN total_driving_minutes > 480 THEN true ELSE false END AS exceeds_shift_limit
FROM route_aggregates
ORDER BY total_driving_minutes DESC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in CTEs. It meets the target criteria: Summary of stops, total driving time, and shift violation status per route.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 Uber and Amazon interviewers?
Interviewers use this problem to test whether candidates write defensive, scalable CTEs 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.