Sub topic 13
Upserting with an External ID Field
This chapter covers upsert, the operation that inserts or updates a record depending on whether it already exists. It focuses on matching records by an external ID field and compares the upsert statement with Database.upsert.
You should already know the following:
- Basic Apex syntax and collections.
- How
insertandupdatestatements work. - How
Database.insertreturnsSaveResultobjects whenallOrNoneis false. - How
try/catchhandlesDmlException.
What upsert does
Upsert combines insert and update in one call. For each record, Salesforce 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.
The key can be one of two things:
- The Salesforce record
Id. If the record has anId, upsert updates it. IfIdis null, upsert inserts. - An external ID field. This is a custom field marked External ID in its definition. It usually holds the key from another system, such as an ERP customer number.
The second case is the common one in integrations. The other system does not know Salesforce IDs. It knows its own keys. With an external ID, you can send data repeatedly without first querying to find out which records already exist.
The statement form
The upsert statement has two forms. The first has no key field:
upsert accounts;With no key, Apex matches on Id. Records with an Id are updated and records without one are inserted.
The second form names the external ID field as a field token:
upsert accounts Account.External_Id__c;Here, Apex matches on External_Id__c. As in every example in this chapter, External_Id__c is a hypothetical custom external ID field on Account.
The statement form follows the same rules as insert and update. It is all-or-none. If any record fails, Apex throws a DmlException and rolls back the whole operation.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme', External_Id__c = 'A-100'),
new Account(Name = 'Globex', External_Id__c = 'G-200')
};
try {
upsert accounts Account.External_Id__c;
} catch (DmlException e) {
System.debug('Upsert failed: ' + e.getMessage());
}The statement gives you no per-record result. If you need to know which records were created and which were updated, use the Database method.
The Database.upsert form
Database.upsert takes the records, an optional external ID field token, and an optional allOrNone flag. It returns a List<Database.UpsertResult>, one entry per input record, in the same order as the input.
// 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());
}
}Passing false as the third argument allows partial success. Valid records are saved, and failures appear in their results instead of being thrown. This is the same behavior you saw with Database.insert.
The overloads you will use most:
| Call | Match key | Failure behavior |
|---|---|---|
| `Database.upsert(records)` | `Id` | All or none |
| `Database.upsert(records, false)` | `Id` | Partial success |
| `Database.upsert(records, Account.External_Id__c)` | External ID | All or none |
| `Database.upsert(records, Account.External_Id__c, false)` | External ID | Partial success |
| `Database.upsert(records, Account.External_Id__c, opts)` | External ID | Controlled by `Database.DMLOptions` |
Reading an UpsertResult
Database.UpsertResult has the same members as SaveResult, plus one more.
| Method | Returns |
|---|---|
| `isSuccess()` | `true` if this record was saved. |
| `getId()` | The ID of the record. It is null if the record failed. |
| `getErrors()` | A list of `Database.Error` objects. It is empty on success. |
| `isCreated()` | `true` if the upsert inserted the record, `false` if it updated an existing one. |
isCreated() is only meaningful when isSuccess() is true. Check success first.
You can use the results to report what an integration run did:
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme', External_Id__c = 'A-100'),
new Account(Name = 'Globex', External_Id__c = 'G-200'),
new Account(External_Id__c = 'X-300') // Name is required, so this fails on insert
};
List<Database.UpsertResult> results = Database.upsert(accounts, Account.External_Id__c, false);
Integer created = 0;
Integer updated = 0;
List<String> failures = new List<String>();
for (Integer i = 0; i < results.size(); i++) {
Database.UpsertResult ur = results[i];
if (ur.isSuccess()) {
if (ur.isCreated()) {
created++;
} else {
updated++;
}
} else {
String key = accounts[i].External_Id__c;
for (Database.Error err : ur.getErrors()) {
failures.add(key + ': ' + err.getStatusCode() + ' - ' + err.getMessage());
}
}
}
System.debug('Created: ' + created + ', updated: ' + updated);
System.debug('Failures: ' + failures);The loop uses the index i to find the input record that matches each result. This works because the result list is in input order. It lets you report the external key of each failure, which is more useful to the source system than a Salesforce ID that does not exist.
How the match works
Several rules follow from this flow.
- Matching on
Id. If theIdis set and no record has it, the upsert fails for that record. It does not insert with your chosenId. - Matching on an external ID. The value in the external ID field on your record decides the match. If it matches one existing record, that record is updated. If it matches none, a new record is inserted with that value.
- Multiple matches. If an external ID value matches more than one existing record, the record fails with a duplicate-match error. This can happen when the field is not marked Unique. Mark the field as unique to prevent it.
- Null key values. A record with a null external ID cannot match anything, so it is inserted. If you do not want that, filter out null keys before the call.
- Case sensitivity. Matching depends on the field's case-sensitivity setting. A unique field that is case-insensitive treats
a-100andA-100as the same key.
Duplicates inside one list
A single upsert call must not contain two records with the same key when that key does not exist yet. The same applies to two records with the same Id. In a list of this kind, the records are processed in one batch, and the second one cannot "see" the first one's insert. The call reports an error for the duplicate.
Remove duplicates before the call. A map keyed by the external ID is the usual way:
List<Account> incoming = new List<Account>{
new Account(Name = 'Acme', External_Id__c = 'A-100'),
new Account(Name = 'Acme Corp', External_Id__c = 'A-100'), // same key
new Account(Name = 'Globex', External_Id__c = 'G-200')
};
Map<String, Account> byKey = new Map<String, Account>();
for (Account a : incoming) {
byKey.put(a.External_Id__c, a); // the last record with a key wins
}
List<Database.UpsertResult> results =
Database.upsert(byKey.values(), Account.External_Id__c, false);
System.debug(results.size()); // 2Decide deliberately which duplicate wins. The code above keeps the last one. If your source data has a timestamp, keep the newest instead.
Relating records through external IDs
An external ID also lets you set a lookup relationship without knowing the parent's Salesforce ID. You build a parent reference object that carries only the external ID value, and assign it to the relationship field.
// Contact upsert that links to its Account by the Account's external ID.
Account parentRef = new Account(External_Id__c = 'A-100');
Contact c = new Contact(LastName = 'Smith', Account = parentRef);
insert c;If no account has External_Id__c = 'A-100', the save fails. The integration does not need a separate query for the parent ID. This pattern saves a query and avoids a map of IDs when you load child records that arrive with a parent key.
Governor limits
Upsert counts against the same DML limits as the other operations. One call counts as one DML statement, whichever form you use, and every record in the list counts toward the total DML rows limit. A list of 200 records in one upsert uses one statement and 200 rows. The same list upserted in a loop uses 200 statements and 200 rows, and can exceed the statement limit. Always pass a collection.
Upsert has one restriction that insert and update do not. The list must hold a single SObject type, and you cannot upsert a list of the generic SObject type with an external ID field token. If the list is of the generic type, the compiler cannot verify the field token. Use a concrete list such as List<Account>. Upsert on a generic list works only with Id matching.
Choosing between the statement and the Database method
| Situation | Better choice |
|---|---|
| A small, trusted set of records where any failure should stop the work | `upsert` statement |
| An integration load where one bad row must not block the rest | `Database.upsert` with `false` |
| You must report which rows were created and which were updated | `Database.upsert` |
| You want errors reported per row, with the external key | `Database.upsert` |
| Field truncation or other options are needed | `Database.upsert` with `DMLOptions` |
The statement is shorter and rolls back everything on a failure. The Database method costs more code, because you must read each result. In exchange, it gives you the per-record detail that integrations depend on.
Common errors
- The field is not an external ID. The compiler or runtime rejects the field token. Mark the field as an external ID in Setup.
- Duplicate keys in one list. You get a duplicate error for the repeated record. Deduplicate with a map first.
- Checking
isCreated()on a failed result. The value has no meaning whenisSuccess()is false. TestisSuccess()first. - Assuming a null key updates. A null external ID always inserts. Filter nulls out or handle them separately.
- Upserting in a loop. Each call uses a DML statement. Collect records and upsert once.
- Ignoring the result list. With
allOrNoneset to false, nothing is thrown for record-level errors. If you do not read the results, failures go unnoticed.
Exercise
You call Database.upsert(accounts, Account.External_Id__c, false) with three accounts. The results show isSuccess() true for all three, and isCreated() is true for the first and false for the other two. What happened to each record, and which two cases would have changed the result for the first record?
Show answer
The first account had an external ID value that matched no existing record, so Salesforce inserted it. The other two matched one existing record each, so Salesforce updated them. The first record would have been updated instead if an account with the same external ID value had already existed. It would have failed if its external ID matched more than one existing record, which can happen when the field is not marked Unique, or if it duplicated another key in the same list.
Exercise
An integration receives 500 rows, some of which repeat the same external ID. Describe how you would load them so that bad rows do not block good ones, and so that you can tell the source system which keys failed.
Show answer
Build a Map<String, Account> keyed by the external ID so that each key appears once, and decide which duplicate wins, for example the newest. Call Database.upsert(map.values(), Account.ExternalId_c, false) once. Loop through the results by index. Because results are in input order, use the same index on the list you passed in to read the external ID of each failed record, and collect the status code and message from getErrors() to send back.