+ Start a Discussion

Counting child records in Account hierarchial relation.

In my scenario one account has many child account records (heirarchial relation) . I want to count these child records. 

I am very new Apex and salesforce . Please guide.

Ritesh AswaneyRitesh Aswaney

assuming a parent - child (2 level hierarchy)


trigger AccountAfter on Account (after insert, after update){


Set<Id> parentAccs = new Set<Id>{};

Map<Id, Integer> childCount = new Map<Id, Integer>{};


for (Account a : trigger.new)

if(a.ParentId != null)

parentAccs.add(a.ParentId);  //collect parent ids


for(Account acc : [Select Id, ParentId from Account where ParentId IN :parentAccs]){

if(childCount.get(acc.ParentId) == null)

childCount.put(acc.ParentId, 0);  //create a counter for parent


childCount.put(acc.ParentId, childCount.get(acc.ParentId) +1); //increment counter




List<Account> accsUpdate = new List<Account>{};


for(Id accId : childCount.keySet())

accsUpdate.add(new Account(Id = accId, ChildCount__c = childCount.get(accId))); //set parent counts


if(accsUpdate != null && !accsUpdate.isEmpty())

Database.update(accsUpdate); //update parent accounts



Thanks ..

Venkatesh C 7Venkatesh C 7
@Ritesh Aswaney
If all the Child account has the same picklist field value, then the parent should be populated with the same value as the child

Could you please help me on this.