Drills › Automate with triggers
Mark parent Accounts in bulk
Automate with triggers · Intermediate · 18 min · Runs in your Salesforce Developer org · Apex Path
Scenario. Account owners want a marker when new Contacts arrive, even during big imports.
Collect Account Ids from new Contacts in a Set and mark every parent Account with at most one query and one update.
What you will learn
Bulk handlers work in steps: collect the parent Ids in a Set, get the parents with one query, change them in memory, then update the list once.
Set<Id> accountIds = new Set<Id>();
for (Contact row : contacts) {
accountIds.add(row.AccountId);
}
Gotcha. A query inside a loop hits the 100-query limit on a big import, even when the DML is outside the loop.
The task
Complete the handler so every Account that gets a new Contact has its Description set to Has new contacts, using at most one query and one update.
Examples:
- one Contact on Account A → A is marked
- two Contacts on Account A and one Contact with no Account → A is marked, and nothing fails
- an Account with no new Contacts → stays as it was
Requirements:
- Collect every non-null AccountId in a
Set<Id>. - Return early when the Set is empty.
- Query those Accounts once, outside any loop. You can also skip the query and build
new Account(Id = ...)records from the Set. - Set each Description to
Has new contactsand update the list once.
Starter code
public class AS_CD9B55EE77FD_ParentMarker {
public static void afterInsert(List<Contact> contacts) {
Set<Id> accountIds = new Set<Id>();
for (Contact contact : contacts) {
}
if (accountIds.isEmpty()) {
return;
}
List<Account> parents = new List<Account>();
}
}
When it passes
Every Account that gets a new Contact is marked, other Accounts stay the same, Contacts with no Account cause no error, and 200 Contacts cost the same queries and DML as 2.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Route Case trigger contexts · Move Opportunity logic to a handler ›