ExpertCTEs & Recursion50 points

Lahore to New York with at most two stops

A customer in Lahore (LHE) wants to reach New York (JFK) and no direct route exists. The sales team needs every possible itinerary built from the routes table with at most 2 stops (at most 3 legs), never visiting the same airport twice, and never flying on after landing at JFK. Each leg uses one directed row of routes.

Task: use a recursive CTE to build the itineraries and return itinerary (airport codes joined by >, for example LHE>DXB>JFK), stops (number of intermediate airports) and total_km (sum of the leg distances). Only itineraries that end at JFK. Sort by total_km ascending, then itinerary A to Z.

The data you can query

Each table is shown with its column types and the first rows, so you can see exactly what the data looks like.

aircraft14 rows
id INTEGERairline TEXTmodel TEXTseats INTEGERdelivered_year INTEGER
1SkyMeridianA3201802017
2SkyMeridianA3201802019
3SkyMeridianA3212002021
4SkyMeridianB787-92902018
5SkyMeridianA350-9003202022
6SkyMeridianB787-92902020

Showing the first 6 of 14 rows.

airports12 rows
code TEXTname TEXTcity TEXTcountry TEXT
JFKJohn F. Kennedy InternationalNew YorkUSA
LHRHeathrowLondonUnited Kingdom
DXBDubai InternationalDubaiUAE
SINChangiSingaporeSingapore
LHEAllama Iqbal InternationalLahorePakistan
ISBIslamabad InternationalIslamabadPakistan

Showing the first 6 of 12 rows.

bookings557 rows
id INTEGERflight_id INTEGERpassenger_id INTEGERcabin TEXTfare_usd INTEGER
1114Economy230
2138Economy180
321Economy380
4222Economy400
5245Economy445
631Economy450

Showing the first 6 of 557 rows.

flights260 rows
id INTEGERflight_no TEXTroute_id INTEGERaircraft_id INTEGERsched_dep TEXTdep_delay_min INTEGERstatus TEXT
1FC1853122025-01-02 07:15:000Completed
2OW3708102025-01-03 05:30:0040Completed
3SM4893552025-01-03 08:00:0025Completed
4SM4153362025-01-03 14:45:0010Completed
5OW5921492025-01-08 16:00:0050Completed
6SM222422025-01-09 08:45:0035Completed

Showing the first 6 of 260 rows.

passengers45 rows
id INTEGERname TEXThome_country TEXTloyalty_tier TEXT
1Ayesha KhanPakistanSilver
2Bilal OkaforAustraliaSilver
3Chen SilvaGermanyNULL
4Diego TanakaAustraliaSilver
5Elena WeberGermanyNULL
6Farid NguyenAustraliaGold

Showing the first 6 of 45 rows.

routes40 rows
id INTEGERorigin TEXTdest TEXTdistance_km INTEGER
1LHEDXB2100
2DXBLHE2100
3ISBDXB2300
4DXBISB2300
5DXBLHR5500
6LHRDXB5500

Showing the first 6 of 40 rows.

Your query runs on SQLite. Write a single SELECT; use LIMIT instead of TOP.

Need a hint?

Carry the path so far as text, and stop recursing when the leg count reaches the limit or you arrive at JFK.