This course is currently a work in progress. Please join the waitlist to receive regular updates.

Upsert statement in apex

The DML upsert statement typically used to insert or update records in the salesforce database. The upsert statement identify the unique records based on unique values on fields like Id OR external Id.

The upsert statement will performs an :

1. Update operation

If there is a match with an exsiting record based on the given unique fields.

2. Insert operation

If there is a not match with an exsiting record based on the unique fields mentioned.

When to use upsert

A common scenario for using the upsert statement is when integrating an external system with salesforce. The external system may not have the salesforce record id, but it can use an external id to modify records in Salesforce.

Following is an example of using an upsert statement to update records in salesforce.

Loading...

In the above example:

  • The variable accountObj creates an instance of an account in apex.
  • The fieldsSAPKey__c, description are populated with values.
  • The DML Upsert statement is used to upsert (insert/update) the account record to the database.