You can use a recursive generic table expression if you use most database brands, with the exception of MySQL and SQLite, as well as several other obscure ones (sorry, I find Firebird obscure). This syntax is an ANSI SQL standard, but Firebird does not yet support it.
Bugfix: Firebird 2.1 supports recursive CTEs, as @Hugues Van Landeghem comments.
Otherwise, see my presentation Models for hierarchical data with SQL for several different approaches.
For example, you can store additional lines for each path in your tree, and not just directly parent / child paths. I call this closing table.
From To Length 1 1 0 1 2 1 1 3 2 1 4 2 1 5 3 2 2 0 2 3 1 2 4 1 3 3 0 4 4 0 4 5 1 5 5 0
Now you can query SELECT * FROM MyTable WHERE From = 1 and get all the descendants of this node.
PS: I would not name the From column because it is a reserved SQL word.
source share