Trigger : Find all Account related Contacts when an Account is Updated.

Scenario: Write trigger syntax to find all Account related Contacts when an Account is Updated.

AccountTrigger
trigger AccountTrigger on Account (after update) {
    AccountTriggerHandler handler = new AccountTriggerHandler();
    if(trigger.isUpdate && trigger.isafter) { 
        handler.findAccountRelatedContacts(trigger.new);
    }
}
AccountTriggerHandler
public class AccountTriggerHandler {
    // Scenario 1: Write trigger syntax to find all Account related Contacts when an Account is Updated.
    public void findAccountRelatedContacts(List<Account> lstAccounts) { 
    	// Note This will work for bulk record as we are using in operator not =:lstAccounts
    	List<Contact> contacts = [SELECT Id From Contact Where AccountId in: lstAccounts];
        System.debug('Account Related Contacts '+ contacts);
    }
}

Scenario

When an Account is updated, you may need the Contacts that belong to it, for example to sync data or create follow-up records. This example shows how to fetch them in a bulk-safe way using a handler class.

How the code works

  1. AccountTrigger runs after update, so the changes are already saved and Trigger.new holds the updated Accounts.
  2. The trigger does not hold the logic itself. It creates the handler and calls findAccountRelatedContacts. Keeping logic in a handler class is a common best practice.
  3. The handler runs one SOQL query that uses IN with the whole list of Accounts, so it works the same for 1 record or 200 records in a transaction.
  4. System.debug prints the Contacts so you can check the result in the debug log.

Why use IN instead of a query inside a loop

One query with IN matches every Account in the list. Running a query for each Account inside a loop would hit the limit of 100 SOQL queries per transaction when many Accounts are updated together.

How to test

  1. Create an Account with two Contacts.
  2. Edit and save the Account.
  3. Open the Debug Log and look for the line starting with Account Related Contacts. It should list both Contacts.

FAQ

Why after update?
The records are already saved and we only need to read related data. Use before update only when you want to change the Account fields without an extra DML.

Is this bulk safe?
Yes. There is one query outside any loop.

Can I update the Contacts too?
Yes. Loop through the Contacts, set the fields, add them to a list, and run a single update outside the loop.

Leave a Reply