ApexSensei

Drills › Change records (DML)

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 update on the list after the loop → Bulk DML used: 1
  • a query by the three Ids → Saved count: 3, Reviewed count: 3 and All tagged: true

Requirements:

  1. Keep the starter's insert and its dmlBefore line. Do not insert again.
  2. In one loop, set every Description to Reviewed and add each Id to createdIds. No DML inside the loop.
  3. After the loop, update the whole list once. Work out DML used as Limits.getDmlStatements() - dmlBefore.
  4. Query only WHERE Id IN :createdIds, count the rows whose Description is Reviewed, and set allTagged to true only when every saved Name starts with AS-BULK-.
  5. Print Bulk DML used:, Saved count:, Reviewed count: and All 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.

Try this drill free

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 ›