Practice Free
HardCTEs High Frequency

Multi-Leg Shipment Route Mileage Accumulator

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.

Solve in Workbench

Problem Statement

Write a recursive CTE to trace the delivery chain starting from the origin port where `leg_number = 1`. Accumulate `cumulative_miles` by adding each leg's distance. Return: 1. `cargo_id` 2. `leg_number` 3. `port_code` 4. `cumulative_miles` Order results by `cargo_id` ascending, then by `leg_number` ascending.

Why Technical Interviewers Ask This

Logistics container tracking systems follow shipping cargo transfers across intermediate transshipment ports, summing cumulative nautical distance from origin to destination.

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 SQL
WITH RECURSIVE route_tracker AS (
        SELECT 
          cargo_id,
          leg_number,
          port_code,
          leg_miles AS cumulative_miles
        FROM shipment_legs
        WHERE leg_number = 1

        UNION ALL

        SELECT 
          l.cargo_id,
          l.leg_number,
          l.port_code,
          (r.cumulative_miles + l.leg_miles) AS cumulative_miles
        FROM shipment_legs l
        JOIN route_tracker r ON l.cargo_id = r.cargo_id AND l.leg_number = r.leg_number + 1
      )
      SELECT 
        cargo_id,
        leg_number,
        port_code,
        cumulative_miles
      FROM route_tracker
      ORDER BY cargo_id ASC, leg_number ASC;
Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in CTEs. It meets the target criteria: Recursive routing hops with cumulative transit mileage.

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

More FAANG SQL Interview Questions

View all questions