Bulk update once
Change records (DML) · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A service must review several Accounts without consuming one DML statement per row.
Prepare three tagged Accounts in a loop and update the collection with one DML statement.
What you will learn
Bulk-safe Apex changes records inside a loop, then saves them all with one DML statement after the loop. Limits.getDmlStatements() tells you how many DML statements have run so far.
for (Account account : accounts) {
account.Description = 'Reviewed';
}
update accounts;
Gotcha. DML inside a loop runs once per record and can hit the limit of 150 DML statements per transaction.
The task
Change three tagged Accounts in a loop, then save them all with one update.
Examples:
- the loop sets each Description to
Reviewed, with no DML inside it - one
updateon the list after the loop →Bulk DML used: 1 - a query by the three Ids →
Saved count: 3,Reviewed count: 3andAll tagged: true
Requirements:
- Keep the starter's
insertand itsdmlBeforeline. Do not insert again. - In one loop, set every Description to
Reviewedand add each Id tocreatedIds. No DML inside the loop. - After the loop, update the whole list once. Work out DML used as
Limits.getDmlStatements() - dmlBefore. - Query only
WHERE Id IN :createdIds, count the rows whose Description isReviewed, and setallTaggedto true only when every saved Name starts withAS-BULK-. - Print
Bulk DML used:,Saved count:,Reviewed count:andAll tagged:in that order.
Starter code
String tag = 'AS-BULK-' + UserInfo.getUserId() + '-' +
String.valueOf(Datetime.now().getTime());
List<Account> accounts = new List<Account>{
new Account(Name = tag + '-A', Description = 'Pending'),
new Account(Name = tag + '-B', Description = 'Pending'),
new Account(Name = tag + '-C', Description = 'Pending')
};
insert accounts;
Integer dmlBefore = Limits.getDmlStatements();
Set<Id> createdIds = new Set<Id>();
When it passes
All three owned Accounts change to Reviewed, and the update step uses exactly one DML statement.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Delete challenge-created records · Upsert: insert or update ›