Count Records in a Related List using Apex

Count Records in a Related List using Apex

Last Updated on October 17, 2021 by Rakesh Gupta

If you want to populate a field with the count of the number of records in a specific related list on a custom object. Without using roll-up summary field, then this blog post is for you.

I will suggest two triggers. First trigger on the child object (to cause a parent-level trigger), and a second trigger to update the field.

Trigger on Parent Object

trigger OnParent on Child__c (after insert, after update, after delete, after undelete) {
  Map<Id,Parent__c> parents = new Map<Id,Parent__c>();
        parents.put(c.ParentLookup__c,new Parent__c(id=c.ParentLookup__c));
    for(Child__c c:Trigger.old)
        parents.put(c.ParentLookup__c,new Parent__c(id=c.ParentLookup__c));
  update parents.values();

Trigger on Child Object

trigger Onchild on Parent__c (before insert, before update) {
    p.RollupCounter__c = 0;
  for(Child__c c:[select id,ParentLookup__c from Child__c where ParentLookup__c in])

The child trigger is responsible for making sure that both the old parent and new parent (if there is change) has their values updated accordingly. The parent trigger actually performs the tallying.

Formative Assessment:

I want to hear from you!  

What is one thing you learned from this post? How do you envision applying this new knowledge in the real world? 

Let me know by Tweeting me at @automationchamp, or find me on LinkedIn.

Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

Preferred Timing(required)

2 thoughts on “Count Records in a Related List using Apex

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.