Wednesday, October 12, 2022

How to get list of all accounts present in account hierarchy in Salesforce

 As a developer, we always get requirement to display records in their hierarchy (Account Hierarchy, Case Hierarchy etc). Using SOQL queries, its really tough to get all accounts in hierarchy as we have to fire multiple SOQL queries to get ultimate parent record id if we are on a record which is 3 or 4 level down in hierarchy. 

Instead of achieving everything using SOQL, we can create formula field "Ultimate Account Id" in account object which will store ultimate account record id on all account records present in account hierarchy. As formula field allows you to refer upto 10 parent, we can easily get list of all account in account hierarchy upto 10 levels.

Below is formula for Ultimate Account Id.

Now if you know account record id, just get Ultimate Account Id field value and then query all accounts which have this ultimate account Id.

Below is static method which can be used to get list of all account present in account hierarchy.

public static list<Account> findAllHierarchyAccounts(string recordId){
list<Account> allAccountList=new List<Account>();
string ultimateAccountId;
for(Account acc:[select Ultimate_Account_Id__c from Account where Id=:recordId]){
for(Account acc:[select id,Name,ParentId
from Account where Ultimate_Account_Id__c=:ultimateAccountId]){
system.debug('***allAccountList size:'+allAccountList);
return allAccountList;

Hope this will help!!


  1. Hi! Great writeup - super helpful. I'm a salesforce novice on the back end but if i wanted to pull the Ultimate Parent account name could i swap the Parent.Id fields with Parent.Name?

  2. Hello Madam and Sir
    Your serious and honest loan offer
    The loan varies from 5,000 to 1,500,000 euros and the documents are available to us, please contact me by email: whats-App +918929509036

  3. Hello, This blog is very informative for every one, It's a Great think to help everyone thanks. Visit our website and find Great products in very cheap price

  4. Artattackk is a well-knowned Website Designing Company In Delhi having 11+years of experience.