Hey everyone, if you find a situation where there is duplicate data having a unique field in common, and you want to delete all and let the unique record be in the org, then this below apex is for you, I am using external Id field which is not unique, which is common in duplicate records.
We have many tools to handle duplicates on creation but few to remove duplicates.
So the scenario is I have below data
Account Name External Id
Chris x 12345
Chris x 12345
Chris x 12345
After running the code we will have
Account Name External Id
Chris x 12345
Here is the below code, you can do tweeks according to you scenario
Hope it helps someone
Thank you
We have many tools to handle duplicates on creation but few to remove duplicates.
So the scenario is I have below data
Account Name External Id
Chris x 12345
Chris x 12345
Chris x 12345
After running the code we will have
Account Name External Id
Chris x 12345
Here is the below code, you can do tweeks according to you scenario
//Collections that we are using
Map<String, List<Id>> mapsOfAccountOfAccount = new Map<String, List<Id>>();
List<Account> accountToDelete = new List<Account>();
//Looping through the accounts records which has external ID
for(Account ac : [Select Id, External_Salesforce_Id__c From Task Where External_Salesforce_Id__c != null]) {
//Creating a map with External as key and list of duplicate records in values
if(mapsOfAccount.containsKey(ac.External_Salesforce_Id__c)) {
mapsOfAccount.get(ac.External_Salesforce_Id__c).add(ts.Id);
} else {
mapsOfAccount.put(ac.External_Salesforce_Id__c, new Set<Id>{ac.Id});
}
}
//Here we are populating a list with those records that we want to delete
for(String ky : mapsOfAccount.keySet()) {
integer i=0;
for(Id ids : mapsOfAccount.get(ky)) {
if(i>0) {
//Create and instance of the records to delete and add to list
accountToDelete.add(new Account(Id = ids));
}
i++;
}
}
delete accountToDelete;
Hope it helps someone
Thank you