Development questions

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

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.

apex-triggertriggercodingscenario