Practice Free
HardWindow Functions High Frequency

Driver Idle Turnaround Time Between Completed Trips

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.

Solve in Workbench

Problem Statement

For each trip in `driver_trip_logs`, look up the driver's previous trip dropoff time using `LAG()`. Return: 1. `trip_id` 2. `driver_id` 3. `pickup_time` 4. `dropoff_time` 5. `prev_dropoff_time`: `LAG(dropoff_time) OVER (PARTITION BY driver_id ORDER BY pickup_time ASC)` Order results by `driver_id` ascending, then by `pickup_time` ascending.

Why Technical Interviewers Ask This

Fleet dispatch algorithms monitor driver idle time between trips. A long gap between the previous dropoff and the next pickup indicates driver deadheading or localized supply shortages.

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 window functions constructs.

Canonical Modern SQL Solution

PostgreSQL 16 / ANSI SQL
SELECT 
        trip_id,
        driver_id,
        pickup_time,
        dropoff_time,
        LAG(dropoff_time) OVER (PARTITION BY driver_id ORDER BY pickup_time ASC) AS prev_dropoff_time
      FROM driver_trip_logs
      ORDER BY driver_id ASC, pickup_time ASC;
Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Window Functions. It meets the target criteria: Trip log showing preceding dropoff timestamp per driver.

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 Window Functions 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.

More FAANG SQL Interview Questions

View all questions