No Results
Search Tips:
- Please consider misspellings
- Try different search keywords
Newer Version Available
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
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.
How Upsert Chooses to Insert or Update
- 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}