Ask the Expert

Fetching rows from trees

I have a problem. The data in a table is stored in the form of a tree. Is there a way I can fetch all the rows for a given part. The part may have sub parts which in turn have subparts. This can go up to any level.

    Requires Free Membership to View

Oracle will let you do this with native SQL by using the CONNECT BY clause of your SELECT statement. For instance, assume I have the following table:

ORA9I SQL> select * from family;

NAME       MOTHER     FATHER
---------- ---------- ----------
adam
eve
susan
bob        eve        adam
janet      susan      
josh       janet      bob

6 rows selected.
In this case, we can see the parents of the children. To see a tree output of this "family", we'll use a query as such:
ORA9I SQL> select lpad(' ',6*(level-1))||name as name
  2  from family
  3  start with mother is null
  4  connect by mother=prior name;

NAME
-----------
adam
eve
      bob
susan
      janet
            josh

6 rows selected.
The START WITH clause tells us which root node to start with. The CONNECT BY clause tells us how to define our tree connections. The LEVEL keyword is just a way of denoting which level we are in the tree. Hopefully, CONNECT BY can give you the output you seek.

For More Information

  • What do you think about this answer? E-mail the editors at editor@searchDatabase.com with your feedback.
  • The Best Oracle Web Links: tips, tutorials, scripts, and more.
  • Have an Oracle or SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
  • Ask your technical Oracle and SQL questions -- or help out your peers by answering them -- in our live discussion forums.
  • Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.

This was first published in May 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: