Rollup Summary Trigger for a Lookup Relationship

Here is a sample Rollup Summary calculation trigger for Lookup relationship. In below example I’m using Account object as parent and Contact object as child.

I’m updating parent object Account record field Total__c with Sum of all related child object Contact records Amount__c field value.

Apex Trigger:

trigger RollUpFromChildToParent on Contact (after insert, after update, after delete, after undelete) {
    
    Set<Id> accountIds = new Set<Id>();
    List<Account> accList = new List<Account>();
    
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){
        for(Contact con : Trigger.new){
            if(con.AccountId != null){
                accountIds.add(con.AccountId); 
            }
        }
    }
    
    If(Trigger.isDelete){
        for(Contact con : Trigger.old){
            if(con.AccountId != null){
                accountIds.add(con.AccountId);
            }
        }
    }
    
    for(AggregateResult aRes : [SELECT AccountId, SUM(Amount__c) Total FROM Contact WHERE AccountId IN :accountIds GROUP BY AccountId]) {
        accList.add(new Account(Id = (Id)aRes.get('AccountId'), Total__c = (Decimal)aRes.get('Total')));
    }
    
    try{
        Update accList;
    }catch(DmlException de){
        System.debug(de);
    }
}