2

I'm trying to do upsert and I get duplicate error on Unique field. Shouldn't upsert take care of whether to update an existing record or to add a new record?

Error:

caused by: System.DmlException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: Unique_ID__c duplicates value on record

Code:

List<MyObject__c> obj = new List<MyObject__c>();
//populate list with data
upsert(obj);
2

You have two records that have Unique_ID__c values that are the same.

| improve this answer | |
  • shouldn't upsert though then treat it as update instead of insert and just update an existing record thus eliminating error? – user569925 Mar 28 '16 at 15:43
  • If both records are in the list when you perform the DML, then no, upsert won't handle that. Also, you must tell the upsert method which External ID field you'll be using (see @Anurag's answer) – Sebastian Kessel Mar 28 '16 at 15:56
2

Try this ,

List<MyObject__c> obj = new List<MyObject__c>();
//populate list with data

upsert obj Unique_ID__c;
| improve this answer | |
2

Upsert works with comparing the Salesforce Id field in your List to determine whether the record need to be updated or inserted. If you want to compare on different field, you need to specify it while doing upsert.

upsert obj MyObject__c.Fields.Unique_ID__;

Document for your reference. Hope it helps.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.