ApexSensei

Drills › Change records (DML)

Handle Database.SaveResult

Change records (DML) · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A small import should keep valid rows while reporting invalid rows for correction.

Let one valid insert succeed while you read the status code of one invalid Account.

What you will learn

Database.insert(records, false) tries every row and returns one SaveResult per record, in order. The second argument is allOrNone: true rolls back on any failure, false saves what it can.

for (Database.SaveResult r : Database.insert(records, false)) {
    if (r.isSuccess()) continue;
    Database.Error e = r.getErrors()[0];
    System.debug(e.getStatusCode());
}

Gotcha. With false, failures do not throw. If you never check the results, bad rows fail silently.

The task

Insert one valid and one invalid Account with partial success, then report what the SaveResult list says.

Examples:

  • Database.insert(accounts, false) returns one result per Account → Result count: 2
  • the Account with a Name saves and the one without fails → Success count: 1 and Failure count: 1
  • the failed result's first error → First error: REQUIRED_FIELD_MISSING

Requirements:

  1. Call Database.insert once with the whole list and false for allOrNone.
  2. Loop over the results and count successes and failures. No DML inside the loop.
  3. For the failed result, store getErrors()[0].getStatusCode() in firstError.
  4. Print Result count:, Success count:, Failure count: and First error: in that order.

Starter code

String tag = 'AS-SAVERESULT-' + UserInfo.getUserId() + '-' +
    String.valueOf(Datetime.now().getTime());
List<Account> accounts = new List<Account>{
    new Account(Name = tag + '-valid', Description = tag),
    new Account(Description = tag + '-missing-name')
};

Integer successCount = 0;
Integer failureCount = 0;
StatusCode firstError;

When it passes

The two results come back in order: one success and one failure whose status code is REQUIRED_FIELD_MISSING. No exception stops the valid insert.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Upsert: insert or update · Savepoint and rollback ›