+ Start a Discussion
Shyamala VaradharajanShyamala Varadharajan 

Update Existing Record before Inserting new record to avoid duplication

I have a Custom Object with 4 fields and 1 Date Field. If I try to create a new record with same values I need to check the old records and if the record persists then need to update the old Record with new Date . This is the code I have tried but the issue is it's updating old record as well as creating new record with same values which cause duplicates.I have written this in before Insert. please help.
public class duplicateHandler {
   public static void triggertocheckDuplicateBeforeInsert(list(List<CustObject> custList){
 Set <String> agencySet = new Set<String>();
Set <String> agencyTypeSet = new Set<String>();
Set <String> advetiserSet = new Set<String>();
Set <String> platformSet = new Set<String>();
Set <Date> startDateSet = new Set<Date>();
List<CustObject> oldList = new List<CustObject>();
        for (CustObject custMap : custList){
        List<CustObject> oldcustList = [SELECT Agency__c,Agency_Type__c,Advertiser__c,Platform__c,Start_Date__c FROM CustObject WHERE Agency__c IN :agencySet AND Agency_Type__c IN :agencyTypeSet AND Advertiser__c IN :advetiserSet AND Platform__c IN :platformSet];
for (CustObject custMap : custList){
  for( CustObject oldCust : oldcustList){
    if(oldcustList.size() > 0){
       if (custMap.Start_Date__c != oldCust.Start_Date__c) {
          oldcustList.Start_Date__c = custMap.Start_Date__c;
update oldList;
This is expected behaviour. If you use addError to throw an error to preven creation of record the update will also fail.

Use Queueable interface to update the old record.
Use addError and throw an error to avoid inserting the new record.

Option 2(Recommended):
Use Duplicate rule and show it on the screen.
PriyaPriya (Salesforce Developers) 
Hey Shyamla,

Kindly implement the duplicate rule in your org for that object

Shyamala VaradharajanShyamala Varadharajan

I want to know how to update old record with the new value while inserting.

Wish 25Wish 25

There is a findDuplicate Class in Apex. You can use that to find if there is a record exist with the same values. If it does, fetch that record using SOQL and update the record. Check below link: