Upsert Record in Apex

Upsert Records – A list containing a mix of new and existing records, you can process insertions and updates to all records in the list by using the upsert statement. Upsert helps avoid the creation of duplicate records.

  • The upsert statement matches the sObjects with existing records by comparing values of one field.
  • You can specify a field to use for matching.
  • If you don’t specify a field name, the upsert statement uses the sObject’s ID to match the sObject with existing records in Salesforce.
  • For custom objects – specify a custom field marked as external ID.
  • For standard objects – you can specify any field that has the idLookup property set to true.

Syntax of Upsert – Using a field name

upsert  sObjectList  Account.Fields.MyExternalId;

Upsert uses the sObject record’s primary key (i.e. ID) field, an idLookup field, or an externalID field to determine whether it should create a new record or update an existing one:

  • If the key is not matched, a new object record is created.
  • If the key is matched once, the existing object record is updated.
  • If the key is matched multiple times, an error is generated and the object record is neither inserted or updated.

// Insert the Josh contact
Contact josh = new Contact(FirstName='Josh',LastName='Kaplan',Department='Finance');
insert josh;

// Josh's record has been inserted so the variable josh has now an ID
// which will be used to match the records by upsert
josh.Description = 'Josh\'s record has been updated by the upsert operation.';

// Create the Kathy contact, but don't persist it in the database
Contact kathy = new Contact(FirstName='Kathy',LastName='Brown',Department='Technology');

// List to hold the new contacts to upsert
List<Contact> contacts = new List<Contact> { josh, kathy };

// Call upsert
upsert contacts;

// <strong>Result-</strong>: Josh is updated and Kathy is created.

Note- If insert was used in this example instead of upsert, a duplicate Jane Smith contact would have been inserted.

API Field Property – 

idLookup   —  Can be used to specify a record in an upsert call. The Id field of each object has this property and some Name fields. There are exceptions, so check for the property in any object you wish to upsert.

One thought on “Upsert Record in Apex

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s