Sub topic 13
Upserting with an External ID Field
This chapter covers upsert, which inserts or updates records in one call, and how an external ID field drives the matching. It assumes you know DML statements, Database methods, allOrNone, and SaveResult-style result objects from earlier chapters.
What upsert does
Upsert looks for an existing record that matches a key. If it finds one, it updates that record. If it finds none, it inserts a new record. You don't need to query first to decide between insert and update, which saves SOQL queries and code.
The key can be one of three things:
- The record
Id, if your records already carry one. - An external ID field, which is a custom field marked "External ID" that holds a key from another system, such as an ERP customer number.
- An idLookup standard field on some objects, such as
Emailon Contact. This chapter focuses on custom external IDs.
An external ID is the usual choice when you sync data from another system. The other system's key is stable, but you don't know the Salesforce Id in advance.
Statement versus Database method
Both forms exist for upsert, as they do for the other operations.
// Statement form: the field token is optional
upsert accounts Account.External_Id__c;// Database form: second argument is the field, third is allOrNone
List<Database.UpsertResult> results =
Database.upsert(accounts, Account.External_Id__c, false);In the statement form, a failure on any record throws DmlException and rolls back the whole operation. In the Database form with allOrNone set to false, valid records are saved and each failure is reported in the results. This is the same trade-off you saw for insert and update.
If you leave out the field, Apex matches on Id. Records with an Id are updated and records without one are inserted.
Reading UpsertResult
Database.upsert returns one Database.UpsertResult per input record, in input order. It has the same isSuccess(), getId(), and getErrors() methods as SaveResult. It also has isCreated(), which is true when the record was inserted and false when it was updated.
// External_Id__c is a hypothetical custom external ID field on Account.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme', External_Id__c = 'A-100'),
new Account(Name = 'Globex', External_Id__c = 'G-200')
};
List<Database.UpsertResult> results = Database.upsert(accounts, Account.External_Id__c, false);
for (Database.UpsertResult ur : results) {
if (ur.isSuccess()) {
System.debug((ur.isCreated() ? 'Created ' : 'Updated ') + ur.getId());
}
}Run it twice. The first run reports Created for both records. The second run reports Updated for both, with the same Salesforce IDs.
Common errors
- Duplicate matches. If more than one existing record has the same external ID value, the upsert fails for that record. Mark the field "Unique" to prevent this.
- Duplicates inside one list. If two records in the same list share an external ID value, the call fails for them. Remove duplicates before the call, for example by keying a
Mapon the external ID. - Missing key value. A record whose external ID is
nullis not matched by that field and is treated as an insert, which can create duplicates. Check the key before you upsert. - Field token typed wrongly. The second argument must be a field token such as
Account.External_Id__c. A string like'External_Id__c'does not compile. - Case sensitivity. Whether
A-100anda-100match depends on how the field was defined. Mark the field "Case sensitive" or normalize values deliberately.
Upsert counts against the same DML limits as other operations: one DML statement, and one row per record in the list.
Exercise
You call Database.upsert(accounts, Account.External_Id__c, false) with 200 accounts. Two records fail validation. How do you find out which records were created and which were only updated, and what happens to the other 198?
Show answer
The 198 valid records are saved, because allOrNone is false and no exception is thrown for record-level errors. The returned list has 200 UpsertResult objects in input order. For each one, check isSuccess(). For successful results, isCreated() is true for inserted records and false for updated ones. For failures, call getErrors() to read the status code, message, and fields.