In my experience, handling bulk operations in Salesforce triggers is essential to ensure that your trigger can efficiently process large volumes of records without hitting Salesforce’s governor limits. The key technique for managing bulk operations is bulkification, which involves writing trigger code that processes multiple records in a single transaction rather than handling each record individually.
trigger AccountTrigger on Account (before update) {
Set<Id> accountIds = new Set<Id>();
// Collect the IDs of all accounts being updated
for (Account acc : Trigger.new) {
accountIds.add(acc.Id);
}
// Query related contacts in bulk
List<Contact> contactsToUpdate = [SELECT Id, Email FROM Contact WHERE AccountId IN :accountIds];
// Perform bulk operations on the queried contacts
for (Contact con : contactsToUpdate) {
con.Email = 'updated@example.com'; // Example logic
}
// Perform a bulk DML update
if (!contactsToUpdate.isEmpty()) {
update contactsToUpdate;
}
}