Database.upsert – how to find which records have inserted/updated based on ExternalId

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

List<Database.upsertResult> 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 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.

Answer

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; index++) {
    if(results[index].isSuccess()) {
        if(results[index].isCreated()) {
            System.debug(lstRecords[index].External_Id__c +' was created');
        } else {
            System.debug(lstRecords[index].External_Id__c +' was updated');
        }
    }
}

Attribution
Source : Link , Question Author : Santanu Boral , Answer Author : sfdcfox

Leave a Comment