Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The very basics
Infinite looping
Processing trees with recursive CTE
Processing graphs with recursive CTE
28. Traveling salesman 3
Summary

## Instruction

Great! Finally, it's time to construct the whole query!

## Exercise

Now, read carefully the instruction below and modify the template in the proper way.

We want to visit every city starting from London. List all paths which start in London and visit all six cities in table city.

Show the following columns:

• path – the list of consecutive cities separated by '->', e.g. London->Oxford->Cambridge...),
• last_lat and last_lon coordinates of the last city in the path,
• total_distance – how much we need to travel altogether,
• count_places – a helper column that should show the number of cities in the path.

Order the results by the total_distance.

You can use the function lat_lon_distance(lat1,lon1,lat2,lon2) that we prepared for you to calculate the distance between two cities.

### Stuck? Here's a hint!

The london CTE should become your anchor member. The second part of the outer query should become the recursive member, but you need to construct the path column by referring to the path from the previous recursive step. In the outer query, show only those paths where the number of cities equals 6 and order the rows in descending order by total_distance.

The last problem is how to construct the termination check. We can use the function position(a IN b), which will return 0 if the string a is not contained in the string b. In other words, we only want to add a certain city if it didn't appear in the path so far.