Managing hierarchical data using ID,ParentID
columns in an RDBMS is known as the Adjacency List model. While very easy to implement and maintain (i.e. insert, update, delete), it's expensive to determine lineage (i.e. ancestors and descendants). As other answers already have written, Oracle's CONNECT BY
will work, but this is an expensive operation. You may be better off representing your data differently.
For your case, the easiest solution might adding a what's called a Hierarchy Bridge table to your schema and adding a LEVEL
column to your original table. The table has columns ID,DescendantID
whereby selecting on ID gives all descendant records, and selecting by DescentantID gives all ancestor records. LEVEL
is necessary on the base table to order records. In this way you make a tradeoff of expensive updates for cheap reads, which is what your question implies you want.
Other possibilities that involve changing your base data include Nested Set and Materialized Path representations. That offer similar tradeoffs of more expensive writes for much cheaper reads. For a complete list of options, pros and cons, and some implementation notes, see my previous question on the topic.