In Apex, the upsert statement is used to perform data insertion and updating operations on custom objects,
based on a specified external ID field. It allows you to insert new records if they don't already exist or update
existing records if they match the external ID value. Here's an example of how to use the upsert statement with
custom objects:
Assuming you have a custom object called "Custom_Object__c" with an external ID field called "External_Id__c":
// Create a new Custom Object record to upsert
Custom_Object__c newRecord = new Custom_Object__c(External_Id__c='123', Name__c='Record Name');
// Use the upsert statement to insert or update the record based on the external ID
upsert newRecord Custom_Object__c.Fields.External_Id__c;
We create a new Custom_Object__c record named newRecord with an external ID value of '123' and a name.
We use the upsert statement to insert or update the newRecord based on the external ID field, which is specified using the Custom_Object__c.Fields.External_Id__c reference.
The upsert statement first checks if a record with the specified external ID value ('123' in this case) exists. If it exists, the existing record is updated with the new values. If no record with that external ID is found, a new record is inserted with the provided values.
Here's another example demonstrating how to upsert multiple records using a list:
List<Custom_Object__c> recordsToUpsert = new List<Custom_Object__c>();
// Create multiple Custom Object records and add them to the list
recordsToUpsert.add(new Custom_Object__c(External_Id__c='456', Name__c='Record A'));
recordsToUpsert.add(new Custom_Object__c(External_Id__c='789', Name__c='Record B'));
// Use the upsert statement to insert or update the records based on the external ID
upsert recordsToUpsert Custom_Object__c.Fields.External_Id__c;
In this example, we create a list of Custom_Object__c records, populate the list with multiple records, and then use the upsert statement to insert or update all the records in the list based on their external ID values.