In database.upsert, how can I find the updated or inserted records based on externalID?

883    Asked by AudreyBerry in Salesforce , Asked on Apr 17, 2023

I am upserting list of records based on externalId as follows:

List results = Database.upsert(lstRecords, CustomObject__c.External_Id__c,true);
The results returns as follows:
(Database.UpsertResult[getErrors=();
                        getId=a1k0j000000P6CmAAK;
                        isCreated=true;
                        isSuccess=true;], 
 Database.UpsertResult[getErrors=();
                        getId=a1k0j000000P6CNAA0;
                        isCreated=false;
                        isSuccess=true;])
The first record is inserted and the 2nd record is updated.

Since I am upserting based on externalId, I need to know for which ExternalId the records have been successfully inserted or updated.


UpsertResult Class doesn't expose any methods. It returns SalesforceId and NOT externalId


I need a results structure like this:

(Database.UpsertResult[getErrors=();
                        getExternalId = '1234';
                        getId=a1k0j000000P6CmAAK;
                        isCreated=true;
                        isSuccess=true;], 
 Database.UpsertResult[getErrors=();
                        getExternalId = '1235';
                        getId=a1k0j000000P6CNAA0;
                        isCreated=false;
                        isSuccess=true;])
What would be the best way to achieve this?
Answered by Camellia Kleiber

The order of the results are the same as the order of the original list. As long as you know the order of the original list (e.g. you didn't do something like Database.upsert(mapRecords.values(), field);), you'll know the order of the results. If you do not know the order, because it's in a map, you can still get the Id from the result (mapRecords.get(result.getId()).ExternalId__c) to get the appropriate record.


Here's how I typically get the results from a DML operation:
Database.UpsertResult[] results = Database.upsert(lstRecords, Object__c.Field__c);
for(Integer index = 0, size = results.size(); index < size>

Your Answer