HardJoins High Frequency
Multi-Leg Freight Hub Transit Connections
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
Self-join `flight_routes` (`leg1` and `leg2`) where `leg1.dest_hub = leg2.origin_hub` and `leg1.origin_hub != leg2.dest_hub`.
Return:
1. `leg1.origin_hub` AS `start_city`
2. `leg1.dest_hub` AS `layover_hub`
3. `leg2.dest_hub` AS `destination_city`
4. `(leg1.flight_hours + leg2.flight_hours)` AS `total_flight_hours`
Filter for routes starting in `'Chicago'`.
Order results by `total_flight_hours` ascending, then by `destination_city` ascending.
Why Technical Interviewers Ask This
Freight dispatchers need to route cargo shipments between cities that don't have direct connections. They self-join flight route segments to find viable two-leg routes with a transfer hub.
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 joins constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
leg1.origin_hub AS start_city,
leg1.dest_hub AS layover_hub,
leg2.dest_hub AS destination_city,
(leg1.flight_hours + leg2.flight_hours) AS total_flight_hours
FROM flight_routes leg1
JOIN flight_routes leg2 ON leg1.dest_hub = leg2.origin_hub
WHERE leg1.origin_hub = 'Chicago'
AND leg1.origin_hub != leg2.dest_hub
ORDER BY total_flight_hours ASC, destination_city ASC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Joins. It meets the target criteria: Two-leg transit routes from Chicago with layover hub and total flight hours.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 Joins 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.