Skip to Main Content
  • Questions
  • Retrieve table hierarchy using foreign key constraint

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Haider.

Asked: July 23, 2007 - 6:19 am UTC

Last updated: May 26, 2022 - 12:52 pm UTC

Version: 9.2.0.8

Viewed 10K+ times! This question is

You Asked

Hi Mr Tom,

I am posting a question first time on your site, hopefully will get an answer soon.

I am trying to get hierarchy of a table using foreign key constraints. I want to pass a table name E.g. Customers and I want all children, grand children and so on of the table customers.

Many thanks
Haider

and Tom said...

http://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817


does more than what you asked for, but shows you the concept...

Rating

  (2 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Retrieve table hierarchy using foreign key constraint

Haider Raza, July 23, 2007 - 12:44 pm UTC

Dear Tom,
Thank you very much for your quick response. Unfortunately the query you sent me gives only 1 level of hierarchy. I am looking for getting hierarhcy from parent to the child most. So for example, a table Customer has two children say Address and Order. Address in turn have another child say local_address and foreign_address and it could go further deep down. So when I pass table name "Customer", I want result like:
Child table Level
----------- ------
Address 1
Order 1
Local_address 2
Foreign_address 2

Hope it more clear now. Sorry for not explaining my question in detail earlier.

Looking forward to hear you soon.

Many thanks
Haider

Retrieve table hierarchy using foreign key constraint - relationship tables

Adriano Policastro, May 25, 2022 - 1:33 pm UTC

Hi Tom,

I need to extend the hierarchy including relationship tables (tables used to implement 'n' to 'm' relationship ).
They have usually 2 fields, with 2 FK pointing to the 2 relates tables.

In these cases previous hierarchy is broken becouse there is no real child of the relationship table.

Do you have any query to solve also this case?

Thanks

Regards

Adriano
Chris Saxon
May 26, 2022 - 12:52 pm UTC

What exactly are you trying to do? A hierarchy across the relationship table? (e.g. CUSTOMERS -> CUSTOMER_ADDRESSES -> ADDRESSES)

If so the problem is the join table is a child of both the others; this means it's no longer a data tree. Depending on what exactly you're trying to do there may be ways around this. You'll need to explain fully what your goal is here.