function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nicholas WillardNicholas Willard 

I would like to know the best way to query a hierarchical database to find parent, grandparent, great-grandparent...

I would like to know the best way to query a hierarchical database to find parent, grandparent, great-grandparent... I think I need to use a combination of Apex and SOQL.  Once I'm at the top I need to find out who the Manager is for all the children.  I am trying everything I can think of to not have query governor issues. Any help would be greatly appreciated.
BalajiRanganathanBalajiRanganathan
You can get upto five level using SOQL.

Select Parent.Parent.Parent.Parent.Parent.ParentId, Parent.Parent.Parent.Parent.ParentId, Parent.Parent.Parent.ParentId, Parent.Parent.ParentId, Parent.ParentId, ParentId From Account
sweetzsweetz
You can use soql relationship queries to access the parent records upto 5-level as mentioned by Balaji.
Nicholas WillardNicholas Willard
Thanks for the advise.  I've tried that and I don't feel it's going to work for what I'm trying to accomplish, as some branches are 2 objects and some are upwards of 5.