function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SarikaPSarikaP 

I have certain records that gets duplicated. Now if I want to keep one record out of that duplicate group and delete others, what is the best way to do?

Hello,

What my question is as follows?

1 a
2 a
3 a
4 b
5 b

I want to get 1 a and 4 b and delete 2 a, 3 a, 5 b.
Is it possible to do?
Raj VakatiRaj Vakati
Yes .. 

First you need to setup the data duplicate rule in salesforce so that it will not allow you to create any new Duplicate records 

Second use some de dupe tools and find the duplciate data and delete it .. 
SarikaPSarikaP
Thanks for your response. Its actually a custom object and while cloning, duplicate records are created. I was able to find using aggregate function how many duplicate records we have as above, but out of these how can i keep one record in a group and delete others using apex, that's my main challenge
Raj VakatiRaj Vakati
well that case you need to check with bussiness .. but there are the options 
  1. Keep the most recent cloned one is not duplicate 
  2. Or ask the user to update some check box filed when they clone ..so tht yiu can keep only the checked records and other are duplicates 
SarikaPSarikaP
This is my code just for reference:

    for(Terms_and_Conditions_Quote__c tc : newLst){
           quoteidset.add(tc.quote__c);
       }
    for(AggregateResult r : [Select Count(Id) dupId, quote__c QId ,Terms_and_Conditions__c TNC from Terms_and_Conditions_Quote__c where quote__c in:quoteidset group by quote__c,Terms_and_Conditions__c having Count(Id) > 1]){
     System.debug('TNCCount with greater than 1' + (Integer)r.get('dupId'));
     if(r != null )
                tncdup.put((Id)r.get('Id'),(Id)r.get('TNC'));  -----> have the id (to delete record), and the value (that's duplicate)
                
       Basically I retrieved the records that are duplicates but now I am stuck how to keep one and delete other from one group, similarly in others.