Trigger to count number of contacts associated with an account ( Bulkified & Uses Aggregate results)

I was working on the similer requirement where I need to check the number of records on the lookup relationship child object and update a field on the parent.

During my search on aggregate results, I found one result which was very easy and thought I will share that here.

Link of the discussion : https://developer.salesforce.com/forums/?id=906F0000000AcdaIAC#ext-gen52

Answered by @Peter_sfdc

trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) {
//---> above handling all states which could see a contact added to or removed from an account
//---> on delete we use Trigger.Old, all else, Trigger.new
List<contact> contacts = Trigger.isDelete ? Trigger.old : Trigger.new;
//---&gt; the Set class rocks for finding the unique values in a list
Set<id> acctIds = new Set<id>();
for (Contact c : contacts) {
//yes, you can have a contact without an account
if (c.AccountId != null) {
acctIds.add(c.AccountId);
}
}
List<account> acctsToRollup = new List<account>();
//****** Here is the Aggregate query...don't count in loops, let the DB do it for you*****
for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount
FROM Contact
WHERE AccountId in: acctIds
GROUP BY AccountId]){
Account a = new Account();
a.Id = (Id) ar.get('AcctId'); //---&gt; handy trick for updates, set the id and update
a.Contact_Count__c = (Integer) ar.get('ContactCount');
acctsToRollup.add(a);
}
//----&gt; probably you'll want to do a little more error handling than this...but this should work.
update acctsToRollup;
}

Comments