[SalesForce] Why does upsert cause a DUPLICATE_VALUE error

I have a custom object, with a Text Name (ID) field. When I upsert two records with identical Name/ID, but otherwise different values, in two separate upsert statement, one record results, as expected.

When I create a list, add these records to the list, and then upsert the list, I get a DUPLICATE_VALUE error. What gives? By definition, upsert should not do this, should it?
Even worse: it doesn't matter whether a record with the identical Name already exists or not, the upsert will fail in both scenarios.

By the way: by default upsert a does not use the Name/ID field as identifying/unique field, as you might expect. You need to do upsert a Name

Complete code:

List<Flight__c> flights = new List<Flight__c>();
Flight__c f1 = new Flight__c();
f1.Name = 'ABC123';
f1.Flight_Number__c = 'ABC';
flights.add(f1);

Flight__c f2 = new Flight__c();
f2.Name = 'ABC123';
f2.Flight_Number__c = '123';
flights.add(f2);

upsert flights Name;

Error message: Line: 12, Column: 1 System.DmlException: Upsert failed.
First exception on row 0; first error: DUPLICATE_VALUE, Duplicate
external id specified: ABC123: [Name]

Name being the standard identifying field of a custom object. You cannot edit the properties of this field, e.g. making it unique or not unique.

Best Answer

So, if I understood correctly, you are passing the same key twice in the list, correct? If that's the case, this is documented

Upserting Records

If the key is matched multiple times, then an error is generated and the object record is neither inserted or updated.

Related Topic