# Write a custom Roll-Up Summary trigger to count the total number of Contacts on an Account (handling Insert, Update, Delete, Undelete, and Account Reparenting).

**Topic:** Development · **Difficulty:** Hard · **Asked at:** Deloitte, PwC, Infosys, Cognizant · **Tags:** apex-trigger, trigger, coding, scenario, rollup

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-custom-roll-up-summary-trigger-to-count-the-total-number-of-contacts-on-an-account-handling-insert

## Answer

Handle all events, collect affected Account Ids (including the **old** AccountId when reparenting), and recompute with an aggregate query.

```apex
trigger ContactRollup on Contact (after insert, after update, after delete, after undelete) {
    Set<Id> accIds = new Set<Id>();
    List<Contact> src = Trigger.isDelete ? Trigger.old : Trigger.new;
    for (Contact c : src) {
        if (c.AccountId != null) accIds.add(c.AccountId);
        if (Trigger.isUpdate) {
            Id oldId = Trigger.oldMap.get(c.Id).AccountId;
            if (oldId != null) accIds.add(oldId);
        }
    }
    Map<Id, Integer> counts = new Map<Id, Integer>();
    for (AggregateResult ar : [SELECT AccountId a, COUNT(Id) c FROM Contact
                                WHERE AccountId IN :accIds GROUP BY AccountId]) {
        counts.put((Id) ar.get('a'), (Integer) ar.get('c'));
    }
    List<Account> toUpdate = new List<Account>();
    for (Id id : accIds) {
        toUpdate.add(new Account(Id = id, Contact_Count__c = counts.containsKey(id) ? counts.get(id) : 0));
    }
    update toUpdate;
}
```
Accounts with no contacts get 0.

---
Source: ForceChallenges · last updated 2026-10-19
