Create Rollup Summary on Lookup Relationship Using Salesforce Apex Trigger : Shubham
by: Shubham
blow post content copied from SalesForce FAQs
click here to view original post
### Summary of Salesforce Rollup Summary on Lookup Relationships In Salesforce, the sales team wanted to display the total number of contact records associated with each account, similar to a roll-up summary field. However, since accounts and contacts are related through a lookup relationship (not a master-detail relationship), creating standard roll-up summary fields is not possible. To overcome this limitation, a custom solution using Salesforce Apex Triggers is implemented. This method automatically updates the contact count on the related account whenever a contact record is added, changed, deleted, or restored. ### Steps to Create a Custom Roll-up Summary Field 1. **Understanding Lookup vs Master-Detail Relationships**: Roll-up summary fields can only be created on master-detail relationships, not lookup relationships. 2. **Creating a Custom Field**: A custom number field (e.g., `Total_Contacts__c`) is created on the Account object to display the total number of related contact records. 3. **Writing the Apex Trigger**: An Apex Trigger is created on the Contact object to handle the logic: - A helper class that calculates and updates the contact count is implemented. - The trigger covers actions after inserting, updating, deleting, or undeleting contacts to ensure the count is accurate. 4. **Implementation Details**: In the helper class, a method calculates the number of contacts related to each account using SOQL queries and updates the custom field accordingly. 5. **Trigger Logic**: The trigger invokes the helper class’s method based on the actions taken on the contact records. ### Code Overview The provided Apex code handles the count of contact records and ensures that the `Total_Contacts__c` field on the Account object is always updated accurately. The example includes a trigger that runs after each contact is modified, ensuring that the count reflects the current state of related contacts. ### Conclusion This approach illustrates a practical way to create a roll-up summary lookalike in Salesforce when dealing with lookup relationships, utilizing custom fields and Apex Triggers effectively. ### Additional Context Salesforce does not allow creating roll-up summaries on lookup relationships by design, directing users to utilize Apex or third-party solutions like Declarative Lookup Rollup Summaries (DLRS) for such requirements. ### Relevant Hashtags for SEO #Salesforce #ApexTriggers #RollupSummary #LookupRelationships #SalesforceDevelopment #CustomFields #CRM #TechTutorial #SalesforceTips #SalesforceApex #DeveloperGuide
In Salesforce, the sales team was using the sales application and wanted to display the total number of contact records related to each account directly on the account record, similar to a roll-up summary field.
But, in Salesforce, accounts and contacts have a lookup relationship, not a master-detail relationship. Salesforce does not allow creating roll-up summary fields on lookup relationships.
As a Developer, I was required to build a custom solution to calculate and display the number of contacts for each account, which functions similarly to a rollup summary field.
In this tutorial, we will learn how to create rollup summary on a lookup relationship using Salesforce Apex Triggers. After that, whenever a contact is inserted, updated, deleted, or undeleted, the trigger automatically updates the count on the related account.
Can We Create a Rollup Summary Field on a Lookup Relationship Object in Salesforce?
No, there is no direct way to create a Salesforce rollup summary field on a lookup relationship; they are only created on the master-detail relationships.
To achieve a similar functionality with a lookup, we must use an Apex trigger, Salesforce Flow, or a third-party AppExchange application, such as a rollup helper or declarative lookup rollup summaries (DLRS).
In the steps below, I will demonstrate what happens when we try to create a rollup summary field on objects that have a lookup relationship.
Here, I will create a custom roll-up summary field on the account object, which will display the total number of contact records associated with that account.
For that, go to the Gear Icon. -> Click on the Setup. -> Select the Object Manager tab. Select the Object on which you want to create the Rollup Summary Field. Here, I’m going to create an Account Object.
In the account setup, click on Fields and Relationships to create a new field and click the New button.
In this step, since we want to display the count of contacts related to an account object, we will select the Rollup Summary option from the data type and click Next.

Next, provide the Field Label and API Name for the rollup summary field, and then click the Next button.

Next, we would normally select the Summarized Object from which we want to summarize the data. In our case, that object would be Contact, since we want to count the number of Contacts related to an Account.
However, because Account and Contact are in a Lookup relationship (not Master-Detail), the contact object does not appear in the list of available summarized objects when creating a rollup summary field.

Create Rollup Summary on Lookup Relationship Using Salesforce Apex Trigger
Since we cannot create a standard rollup summary field on a lookup relationship directly, we will write an Apex Trigger on the Contact object and implement the business logic into a Helper Class.
The very first step is to create a custom Number field on the Account object, which will be used to display the total number of related Contacts. Let’s name this field Total_Contacts__c.
This field will function as a roll-up summary field, but instead of being updated automatically by Salesforce, it will be updated through our Apex Trigger logic whenever any Contact record is inserted, updated, deleted, or undeleted.

First, we will create a Helper Class to implement the logic that calculates the number of Contact records related to an Account and updates the custom field (Total_Contacts__c) on the Account record.
To create the class, go to Setup → Developer Console -> File -> New -> Apex Classes → and then write the Apex class with the required logic.
In the method, I declared a list collection that gets the contact records from the trigger, and then we use this List to store new and old contact records.
After that, we use a for loop to iterate over the Account records stored in the list. To get only unique records, we then store them in a Set collection.
Then, using a Map collection, we mapped the Account Name to the corresponding Account record in Salesforce, which we retrieved using a SOQL query. That means we are creating a key-value pair.
Next, by using the COUNT() operator in a SOQL query, we will calculate the total number of Contact records related to each Account.
After fetching this count, we will update the custom Number field (Total_Contacts__c) on the Account object so that it always displays the correct number of related Contacts.
public class ContactTriggerHandler {
public static void updateContactCount(List<Contact> newList, List<Contact> oldList, Boolean isDelete) {
//Declare the variable first
Set<Id> accountIds = new Set<Id>();
// Collect Account Ids from new records
if(newList != null){
for(Contact con : newList){
if(con.AccountId != null){
accountIds.add(con.AccountId);
}
}
}
// Collect Account Ids from old records (for deletes/updates)
if(oldList != null){
for(Contact con : oldList){
if(con.AccountId != null){
accountIds.add(con.AccountId);
}
}
}
if(accountIds.isEmpty()){
return; // nothing to process
}
// Count Contacts for each Account
Map<Id, Integer> accountContactCount = new Map<Id, Integer>();
for(AggregateResult ar : [
SELECT AccountId, COUNT(Id) totalContacts
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
]){
accountContactCount.put((Id)ar.get('AccountId'), (Integer)ar.get('totalContacts'));
}
// Update Account with Contact count
List<Account> accountsToUpdate = new List<Account>();
for(Id accId : accountIds){
Account acc = new Account(Id = accId);
acc.Total_Contacts__c = accountContactCount.containsKey(accId) ? accountContactCount.get(accId) : 0;
accountsToUpdate.add(acc);
}
if(!accountsToUpdate.isEmpty()){
update accountsToUpdate;
}
}
}

In the trigger below, we have defined the object on which the trigger is created and the trigger events that will fire the logic. Here, the trigger is written on the Contact object, and it runs after insert, update, delete, and undelete.
These events are required because any of these operations can change the number of contacts related to an account, and we want the count on the Account to stay updated.
Then, using the helper class name, call the methods in the order you want to execute.
trigger ContactTriggers on Contact (after insert, after update, after delete,
after undelete) {
if(Trigger.isAfter){
if(Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete || Trigger.isUndelete){
ContactTriggerHandler.updateContactCount(Trigger.new, Trigger.old,
Trigger.isDelete);
}
}
}

Proof of concept:
In the screenshot below, you can see in the Related tab of the Account record, under the contacts section, there are four existing Contact records related to the Agro Tech Account.

As you open the Detail tab, the custom field Total_Contacts__c on the account displays a value of 4, because our trigger has automatically counted the related contacts and updated the field.

In this way, we can create a rollup summary on a lookup relationship using Salesforce Apex Trigger.
Conclusion
I hope you have got an idea about how we can build a custom roll-up summary field on the Account object to display the total number of related Contacts.
Since Salesforce does not allow roll-up summaries on Lookup relationships, we solved this by creating a custom number field, writing a trigger on the Contact object, and moving the logic into a helper class.
You may like to read:
- Before Insert Validation in Salesforce Trigger [With Examples]
- Restrict Record Deletion Using Salesforce Trigger
- Before vs After Triggers in Salesforce: When to Use & Why
The post Create Rollup Summary on Lookup Relationship Using Salesforce Apex Trigger appeared first on SalesForce FAQs.
September 04, 2025 at 10:18PM
Click here for more details...
=============================
The original post is available in SalesForce FAQs by Shubham
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Post a Comment