How to upsert using External Id using Salesforce Apex?

How to upsert using External Id using Salesforce Apex?

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

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

Sample Code:

List < Account > listAccounts = new List < Account >();

for ( Integer i = 0; i <= 5; i++ ) {
    
    listAccounts.add(
        new Account(
        	Name = 'Test ' + i,
            External_ID__C = String.valueOf( i ),
            Industry = 'Technology'
        )
    );
    
}

upsert listAccounts Account.Fields.External_ID__c;

here listAccounts is the List and External_ID__c is an External field.

Leave a Reply