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 passand upsert again →Second upsert created: false - a query by the saved Id →
Match count: 1andSaved description: Second pass
Requirements:
- Call
Database.upserton the Account and keep theDatabase.UpsertResultit returns. - Save the Id the first upsert gave the Account.
- Set Description to
Second passand upsert the same Account again. - Query only by the saved Id.
- Print
First upsert created:andSecond upsert created:fromisCreated(), thenMatch count:andSaved 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.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.