# Update the child Contacts count if Number_of_Locations__c on Account increases or decreases on update.

**Topic:** Development · **Difficulty:** Hard · **Asked at:** Deloitte, Persistent, Nagarro · **Tags:** apex-trigger, trigger, coding, scenario

Read it on the site: https://www.forcechallenges.com/interview-questions/update-the-child-contacts-count-if-number-of-locations-c-on-account-increases-or-decreases-on-update

## Answer

On `after update`, compare new and old `Number_of_Locations__c`. If it increased, insert the difference; if it decreased, delete that many Contacts.

```apex
trigger AccountTrigger on Account (after update) {
    List<Contact> toInsert = new List<Contact>(), toDelete = new List<Contact>();
    Map<Id, Integer> removeCount = new Map<Id, Integer>();
    for (Account a : Trigger.new) {
        Integer n = a.Number_of_Locations__c == null ? 0 : (Integer) a.Number_of_Locations__c;
        Integer o = Trigger.oldMap.get(a.Id).Number_of_Locations__c == null ? 0 : (Integer) Trigger.oldMap.get(a.Id).Number_of_Locations__c;
        if (n > o) for (Integer i = o + 1; i <= n; i++) toInsert.add(new Contact(LastName = a.Name + ' Location ' + i, AccountId = a.Id));
        else if (n < o) removeCount.put(a.Id, o - n);
    }
    for (Account a : [SELECT Id, (SELECT Id FROM Contacts ORDER BY CreatedDate DESC) FROM Account WHERE Id IN :removeCount.keySet()]) {
        Integer k = removeCount.get(a.Id);
        for (Integer i = 0; i < k && i < a.Contacts.size(); i++) toDelete.add(a.Contacts[i]);
    }
    insert toInsert; delete toDelete;
}
```

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