+ Start a Discussion
Nar_7Nar_7 

Calculate no. of child records

Hi Folks, I am new to salesforce and wolud like to know, "How to calculate no of child records to a parent object without using trigger". 
Any help will be appreciated, Thank you very much beforehand.
Katie GrauerKatie Grauer
You can try a roll-up summary field. That should give you a number.
Ravi Dutt SharmaRavi Dutt Sharma
If there is a master detail relationship between the parent and child object, then as Katie mentioned , you can go for a rollup summary field.
If it is a lookup relationship between the parent and child object, then you need to create a trigger on child object that will update the count field (you need to create a custom field to store the count of child records) on parent object. You need to handle the insert, delete and undelete events in this trigger. You may also have to handle the update event in case your lookup relationship allows reparenting of records.
JyothsnaJyothsna (Salesforce Developers) 
Hi,

If there is a master-detail relationship between the parent and child objects, then you can use rollup summary field.

While your formula fields calculate values using fields within a single record, roll-up summary fields calculate values from a set of related records, such as those in a related list. You can create roll-up summary fields that automatically display a value on a master record based on the values of records in a detailed record. These detail records must be directly related to the master through a master-detail relationship.

If it is a lookup relationship, then you can create a Trigger on the child object.

Hope this helps you!
Best regards,
Jyothsna
Amit Chaudhary 8Amit Chaudhary 8
Hi ,
You can do this by below two option :-

Option 1:-
If you have mater detail relation ship then you can try the rollup-summery field.

Option 2:-
You can try the same with trigger. Please check below post for code.
1) http://www.infallibletechie.com/2014/11/how-to-count-number-of-child-records-in.html
2) https://github.com/abhinavguptas/Salesforce-Lookup-Rollup-Summaries
3) http://automationchampion.com/2013/02/13/count-records-in-a-related-list/
4) https://www.sundoginteractive.com/blog/rollup-summary-with-a-lookup-field-salesforce

Sample code.
trigger HobbyTrigger on Hobby__c (after insert, after delete) {
    map<Id, Integer> mapEmpIdHobbyCount = new map<Id, Integer>();
    if(trigger.isInsert) {
        for(Hobby__c hob : trigger.new) {
            if(hob.Employee__c != null) {
                if(!mapEmpIdHobbyCount.containsKey(hob.Employee__c)) {
                    mapEmpIdHobbyCount.put(hob.Employee__c, 1);
                } else {
                    mapEmpIdHobbyCount.put(hob.Employee__c, mapEmpIdHobbyCount.get(hob.Employee__c) + 1);
                }
            }
        }
    } else {
        for(Hobby__c hob : trigger.old) {
            if(hob.Employee__c != null) {
                if(!mapEmpIdHobbyCount.containsKey(hob.Employee__c)) {
                    mapEmpIdHobbyCount.put(hob.Employee__c, -1);
                } else {
                    mapEmpIdHobbyCount.put(hob.Employee__c, mapEmpIdHobbyCount.get(hob.Employee__c) - 1);
                }
            }
        }
    }
    if(mapEmpIdHobbyCount.size() > 0) {
        List<Employee__c> listEmp = [SELECT Id, Number_of_Hobbies__c FROM Employee__c WHERE Id IN : mapEmpIdHobbyCount.keySet()];
        
        for(Employee__c emp : listEmp) {
            emp.Number_of_Hobbies__c += mapEmpIdHobbyCount.get(emp.Id);
        }
        
        update listEmp;
    }
}
Let us know if this will help you

Thanks
Amit Chaudhary

 
Mahesh DMahesh D
Hi Nar,

I would request you to inform us about the relationship between child and parent objects.

Scenario 1: If the Relationship is Master-Detail:
       Then you can go to Parent object and Create a custom field with Roll-Up Summary and select the roll-up type as Count as shown below:

User-added image

Scenario 2: If the Relationship is Lookup:
        Then we have to implement it by writing the Trigger:

To calculate Rollup Summary using the Trigger, you need to follow below:

Need to consider all DML operations like insert, update, delete and undelete of child records.


Insert of Child record:
     --> Need to write an after insert trigger to update the Parent record with calculated count value.
Update of Child record:
     --> Make sure that the Parent information got changed.
     --> Need to write an after update trigger and get both old and new Parent information and perform the re-calculation of count.
Delete of Child record:
     --> Need to write an after delete trigger to update the Parent record with re-calculated count value.
Undelete of Child record:
     --> Need to write an after undelete trigger to update the Parent record with re-calculated count value.

Also check the below code:
 
//
// ContactCount trigger to handle the roll up summary on Account
//
trigger ContactCountNew on Contact (after insert, after delete, after undelete, after update) {
    set<Id> accIdSet = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Contact con: Trigger.new){
            if(Trigger.isInsert || Trigger.isUndelete || (con.AccountId != Trigger.oldMap.get(con.Id).AccountId))
                accIdSet.add(con.AccountId);
        }
    }
    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Contact con: Trigger.old){
            if(Trigger.isDelete || (con.AccountId != Trigger.newMap.get(con.Id).AccountId))
                accIdSet.add(con.AccountId);
        }
    }    
    
    if(!accIdSet.isEmpty()) {
        List<Account> accList = [select Id, Count__c, (Select Id from Contacts) from Account Where ID IN: accIdSet];
        
        for(Account acc : accList){
            System.debug('Contacts--->'+acc.Contacts.size());
            acc.Count__c = acc.Contacts.size();
        }
        update accList;
    }
}

Also look into below posts:

1) http://blog.jeffdouglas.com/2011/08/23/salesforce-trigger-when-rollups-summaries-not-possible/
2) https://success.salesforce.com/answers?id=90630000000h3mNAAQ
3) https://developer.salesforce.com/forums/?id=906F00000008yWuIAI
4) https://github.com/abhinavguptas/Salesforce-Lookup-Rollup-Summaries
5) http://www.iterativelogic.com/developing-custom-apex-rollup-summary-field-logic/ (http://www.iterativelogic.com/developing-custom-apex-rollup-summary-field-logic/)

Please do let me know if it helps you.

Regards,
Mahesh
Kt YadavKt Yadav
Hi ,

Please go through below link you will find all the scenarios like delete, update and insert count.
https://sfdceinstien.wordpress.com/2019/01/19/custom-lookup-maintain-number-of-child-count-on-parent-object-in-case-of-lookup-relationship-in-saleforce/

Regards,
Keerti Yadav
 
Suresh MeghnathiSuresh Meghnathi

Case 1: If the Relationship is Master-Detail:
       Then you can create a custom field with Roll-Up Summary on the Parent object and select the roll-up type as Count.
Case 2: If the Relationship is Lookup:
        Then we have to write the Trigger.
Case 3: You can use the subquery or Relationship Query as below:

SOQL for two standard objects. Let’s say Account as a parent object and Contact as a child object.
Query to fetch the all Contact which is associated with Account ‘Account1’.
// When a record is fetched from Contact
SELECT Name, Account.Name FROM Contact where Account.Name = 'Account1'
// When a record is fetched from Account.
// Contacts is a child relationship name of Contact object.
SELECT Name, (SELECT Name FROM Contacts) FROM Account where Name = 'Account1'