ApexSensei

Drills › Change records (DML)

Upsert: insert or update

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

Scenario. An integration may receive a new record first and then the same Salesforce record with changes.

Upsert one Account twice with Database.upsert and use isCreated() to show the first call inserts and the second updates.

What you will learn

upsert inserts a record when no match exists and updates it when one does. By default it matches on Id. Database.upsert returns an UpsertResult, and isCreated() is true only when it inserted.

Database.UpsertResult result = Database.upsert(account);
upsert customers Account.Fields.Customer_Number__c;

The second line matches on an External ID field instead of Id.

Gotcha. That field must exist in the org and be marked External ID.

The task

Upsert one tagged Account twice with Database.upsert: the first call inserts it and the second updates it.

Examples:

  • first Database.upsert(account), with no Id yet → First upsert created: true
  • set Description to Second pass and upsert again → Second upsert created: false
  • a query by the saved Id → Match count: 1 and Saved description: Second pass

Requirements:

  1. Call Database.upsert on the Account and keep the Database.UpsertResult it returns.
  2. Save the Id the first upsert gave the Account.
  3. Set Description to Second pass and upsert the same Account again.
  4. Query only by the saved Id.
  5. Print First upsert created: and Second upsert created: from isCreated(), then Match count: and Saved description:.

Starter code

String tag = 'AS-UPSERT-' + UserInfo.getUserId() + '-' +
    String.valueOf(Datetime.now().getTime());
Account account = new Account(Name = tag, Description = 'First pass');

Database.UpsertResult firstResult;
Id insertedId;
Database.UpsertResult secondResult;
List<Account> matches = new List<Account>();

When it passes

The first upsert inserts (isCreated true), the second updates the same row (isCreated false), and one row holds the second Description.

Try this drill free

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

‹ Bulk update once · Handle Database.SaveResult ›