# When an Account's OwnerId changes, change the OwnerId of all its related open Opportunities and Contacts.

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Accenture, Capgemini, Cognizant · **Tags:** apex-trigger, trigger, coding, scenario

Read it on the site: https://www.forcechallenges.com/interview-questions/when-an-account-s-ownerid-changes-change-the-ownerid-of-all-its-related-open-opportunities-and-contacts

## Answer

Use `after update` on Account, detect OwnerId changes, then update related open Opportunities and Contacts.

```apex
trigger AccountTrigger on Account (after update) {
    Map<Id, Id> newOwner = new Map<Id, Id>();
    for (Account a : Trigger.new) if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId) newOwner.put(a.Id, a.OwnerId);
    if (newOwner.isEmpty()) return;
    List<SObject> toUpdate = new List<SObject>();
    for (Opportunity o : [SELECT Id, AccountId FROM Opportunity WHERE AccountId IN :newOwner.keySet() AND IsClosed = false]) {
        o.OwnerId = newOwner.get(o.AccountId); toUpdate.add(o);
    }
    for (Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :newOwner.keySet()]) {
        c.OwnerId = newOwner.get(c.AccountId); toUpdate.add(c);
    }
    update toUpdate;
}
```
Note: updating a mixed `List<SObject>` works when records are sorted by type; otherwise split into two lists to avoid chunk limits.

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