Newer Version Available

This content describes an older version of this product. View Latest

Upsert Statement

The upsert DML operation creates new sObject records and updates existing sObject records within a single statement, using an optional custom field to determine the presence of existing objects.

Syntax

upsert sObject​​ opt_external_id

upsert sObject[]​​ opt_external_id

opt_external_id​​ is an optional variable that specifies the custom field that should be used to match records that already exist in your organization's data. This custom field must be created with the External Id attribute selected. Additionally, if the field does not have the Unique attribute selected, the context user must have the “View All” object-level permission for the target object or the “View All Data” permission so that upsert does not accidentally insert a duplicate record.

If opt_external_id​​ is not specified, the sObject record's ID field is used by default.

Custom field matching is case-insensitive only if the custom field has the Unique and Treat "ABC" and "abc" as duplicate values (case insensitive) attributes selected as part of the field definition. If this is the case, “ABC123” is matched with “abc123.” For more information, see “Creating Custom Fields” in the Salesforce online help.

Note

How Upsert Chooses to Insert or Update

Upsert uses the sObject record's primary key (or the external ID, if specified) to determine whether it should create a new object record or update an existing one:
  • If the key is not matched, then a new object record is created.
  • If the key is matched once, then the existing object record is updated.
  • If the key is matched multiple times, then an error is generated and the object record is neither inserted or updated.

You can use foreign keys to upsert sObject records if they have been set as reference fields. For more information, see Field Types in the Object Reference for Salesforce and Force.com.

Example

This example performs an upsert of a list of accounts.

1List<Account> acctList = new List<Account>();
2// Fill the accounts list with some accounts
3
4try {
5    upsert acctList;
6} catch (DmlException e) {
7   
8}

This next example performs an upsert of a list of accounts using a foreign key for matching existing records, if any.

1List<Account> acctList = new List<Account>();
2// Fill the accounts list with some accounts
3
4try {
5    // Upsert using an external ID field
6    upsert acctList myExtIDField__c;
7} catch (DmlException e) {
8   
9}