Solving the Traveling Salesman Problem with Postgres Recursive CTEs

Recursive CTEs are more powerful – they reference themselves and allow you to explore hierarchical data. While that may sound complicated, the underlying concept is very similar to a for loop in other programming languages.

.. Here’s a simple recursive CTE that generates the numbers 1 to 10. The anchor member selects the value 1, and the recursive member adds to it up to the number 10:

with recursive incrementer(prev_val) as (
select 1 — anchor member
union all
select — recursive member
incrementer.prev_val + 1
from incrementer
where prev_val < 10 -- termination condition ) select * from incrementer