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

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');
        }
    }
}

Tags:

Upsert

Apex