Sub topic 2
Sets, Maps, and Lists: The Bulkification Toolkit
Assume you know basic Apex syntax, collections, SOQL, DML, and trigger events. Bulkification means writing code that handles many records efficiently in one transaction.
Collections for Bulkification
A Set stores unique values. Use it to collect record IDs for one query. A Map stores key-value pairs. Use it to find queried records quickly by ID. A List stores an ordered group of records for later processing or DML.
flowchart LR
A[Trigger records] --> B[Set of parent IDs]
B --> C[One SOQL query]
C --> D[Map keyed by ID]
D --> E[Process each trigger record]
E --> F[List of changed records]
F --> G[One DML operation]A common bulk pattern is:
- Collect IDs in a
Set<Id>. - Query related records into a
Map<Id, SObject>. - Build a
List<SObject>for records that need changes. - Perform one DML operation.
Moving SOQL out of Loops
A SOQL query inside a loop runs once per record. This can exceed Salesforce’s per-transaction query limit when a trigger receives many records.
trigger ContactBefore on Contact (before insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact contactRecord : Trigger.new) {
if (contactRecord.AccountId != null) {
accountIds.add(contactRecord.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact contactRecord : Trigger.new) {
Account accountRecord = accounts.get(contactRecord.AccountId);
if (accountRecord != null) {
contactRecord.Description =
'Industry: ' + accountRecord.Industry;
}
}
}The query runs once, regardless of how many contacts share those accounts. The map lookup is efficient and avoids another query.
> callout note > Always handle empty IDs and missing related records. A lookup can return null, especially when a lookup field is optional.
Collecting Records and Running DML Once
DML inside a loop can exceed the DML statement limit and creates unnecessary transaction overhead. Add records to a list, then save the list once.
trigger AccountAfter on Account (after insert) {
List<Task> tasks = new List<Task>();
for (Account accountRecord : Trigger.new) {
tasks.add(new Task(
WhatId = accountRecord.Id,
Subject = 'Follow up'
));
}
if (!tasks.isEmpty()) {
insert tasks;
}
}This trigger uses one insert statement for the complete batch.
Exercise
Which collection should you use to gather unique Account IDs before a SOQL query?
Show answer
Use a Set<Id>.