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
Waqar Hussain SFWaqar Hussain SF 

how to delete duplicate records from database?

Too many duplicate records in a custom_object__c, and have a custom field id__c, which is unique.
from Id__c I can find duplicate records. Now I want to delete duplicate records but remain 1 record. how this is possible.
I tried batch jobs. but didn't find any solution.
Best Answer chosen by Waqar Hussain SF
Shashikant SharmaShashikant Sharma
1. You could do it by batch make it stateful

2. Create a Set in which keep record.Id__c 
Set<Datatype of Id__c> setRecordsToKeep = new Set<Datatype of Id__c>();
3. in execute method keep
List<custom_object__c> listRecordsToDelete = new List<custom_object__c>();

for( custom_object__c obj : scope ) {

// set's method add will return false if item is not been abled to add as it exists already
if(  !setRecordsToKeep.add(obj.Id__c) ) {
listRecordsToDelete.add( obj );
}
}

4. in finish method
delete listRecordsToDelete;

let me know if any questions or  issues.

All Answers

Shashikant SharmaShashikant Sharma
1. You could do it by batch make it stateful

2. Create a Set in which keep record.Id__c 
Set<Datatype of Id__c> setRecordsToKeep = new Set<Datatype of Id__c>();
3. in execute method keep
List<custom_object__c> listRecordsToDelete = new List<custom_object__c>();

for( custom_object__c obj : scope ) {

// set's method add will return false if item is not been abled to add as it exists already
if(  !setRecordsToKeep.add(obj.Id__c) ) {
listRecordsToDelete.add( obj );
}
}

4. in finish method
delete listRecordsToDelete;

let me know if any questions or  issues.
This was selected as the best answer
Waqar Hussain SFWaqar Hussain SF
Hi Shashikant Sharma... Thanks for your reply.
But Id__c is a custom field. how can I make Set of custom fields?
Shashikant SharmaShashikant Sharma
What is the data type of ID__c field like if it is string then you need to do :

Set<String>
setRecordsToKeep = new Set<String>();

and populate this set with value in ID__c

setRecordsToKeep.add(  obj.Id__c );