[SalesForce] Upsert with External ID: DUPLICATE_VALUE Error

I'm trying up upsert Asset records with an external Id and am getting the DUPLICATE_VALUE error which makes no sense to me: I want it to UPDATE the record if it finds a duplicate, that's what UPSERT means.

Asset a = new Asset();
a.accountId = '001D000000nbvbn';
a.Name =  'foo';
a.SerialNumber = 'bar';
a.Quantity=221;
a.AssetID__c = '244601-WWPC_CONTRCS25';
upsert a; 

I've checked and AssetID__c '244601-WWPC_CONTRCS25' exists once (/02iD000000KRoJt) in the database.

17:43:32.13 (97251484)|EXCEPTION_THROWN|[12]|System.DmlException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: AssetID__c duplicates value on record with id: 02iD000000KRoJt: []
17:43:32.13 (97704106)|FATAL_ERROR|System.DmlException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: AssetID__c duplicates value on record with id: 02iD000000KRoJt: []

What am I missing? It almost seems as if the system is parsing 'upsert' as 'insert'. Indeed if I change my code to 'insert' I get the same error.

Best Answer

You need to specify the key field - in this case, it is just using Id as the key. So your upsert should look something like:

upsert a AssetID__c; 
Related Topic