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
Srividya SharmaSrividya Sharma 

Account Hierarchy Query

Hi

 

Can anyone tell me how to construct the query to obtain the account hierarchy for a given account?

 

select Id, ParentId from Account where Id=123

 

this gives the parentid for this account.

 

How do I go from here?

 

Any help is appreciated.

 

Thanks.

 

 

Best Answer chosen by Admin (Salesforce Developers) 
MiddhaMiddha

If you have a small set of Accounts or you can add some other filter criteria, you can query all the Accounts and then use a recursive method to create a hirarchy.

 

Or

 

you can also use this querye: Select Parent.Parent.Parent.Parent.Parent.ParentId, Parent.Parent.Parent.Parent.ParentId, Parent.Parent.Parent.ParentId, Parent.Parent.ParentId, Parent.ParentId, ParentId From Account

 

to fetch parents till 5 level to get parents upto 5 level above. Have not tried this query, but should work.

All Answers

MiddhaMiddha

If you have a small set of Accounts or you can add some other filter criteria, you can query all the Accounts and then use a recursive method to create a hirarchy.

 

Or

 

you can also use this querye: Select Parent.Parent.Parent.Parent.Parent.ParentId, Parent.Parent.Parent.Parent.ParentId, Parent.Parent.Parent.ParentId, Parent.Parent.ParentId, Parent.ParentId, ParentId From Account

 

to fetch parents till 5 level to get parents upto 5 level above. Have not tried this query, but should work.

This was selected as the best answer
Srividya SharmaSrividya Sharma

Thank you for this query.

 

Unfortunately, even in Force.com explorer, only the following query works:

 

Select  Parent.ParentId, ParentId From Account

 

This gives just 2 levels.

 

Any furher help for getting all the levels or at least 5 levels would be greatly appreciated.

 

GowthamSenGowthamSen

Hi,

 

I tried the same way for Contact. But seems not working.

 

SELECT Contact.Name , Name FROM Contact

 

Here Contact is having a field "Reports To" defines the recursive relationship to table Contact.

 

When I run the above query to get the Supervisor for Name,  I got the following error:

 

INVALID_FIELD:
SELECT Contact.Name , Name FROM Contact
                      ^
ERROR at Row:1:Column:23
duplicate field selected: Name

 

Could you please help me here to solve the issue?

 

I understand the first solution explained in your reply, but I donno just how to do that? Could you please give me some guidance here?

 

Best Regards

Gowtham