This is from a homework question. We solved it by building the SQL query dynamically. But we are interested if it is possible to do with pure SQL.
A simplification of what is desired:
There is a table with two columns: source id and destination id. Given an id and a number n, we need to find all id of distance smaller equal n from the given id.
Clarification Edit:
Think about the table as representing web-links. If the row (1,3) appears in the table, it means that web-page 1 has a link to web-page 3.
We need to find all webpages that are reachable from a starting web-page with n clicks or less.
Since it is a “curiosity” question, use whatever SQL implementation you prefer.
“Pure SQL” means everything that fits into the “structured query style”. Using loops is not considered “pure SQL” (for the sake of the question).
You cannot express transitive closure using relational algebra or pure old SQL, so a general solution for any N is not possible.
The best you can do is choose the N at “compile time” and use lots of joins, as you already do in the dynamically generated query approach.