For some reason there are created duplicated records for certain custom object.

Some of these records are inserted (incorrectly) exactly 2 times.

Duplicated records have the same data in fields (only Ids are different) - for example: recordName1(Name='a1', Status='On'), recordName1(Name='a1', Status='On'), recordName2(Name='a2', Status='Off'), recordName2(Name='a2', Status='Off') and I want to deduplicate this records in Apex (repeatedly).

How can I delete only duplicated records or take old records and delete them and insert records after deduplication?

How SOQL query to do this would look like? There is object Object__c and fields like Name, Status__c, Location__c. There are only 24 records to handle so time complexity won't be a problem.

  • What have you tried so far? May 26, 2020 at 9:29
  • I tried to find a place in the code that causes this error but I can't find this because numbers of lines of code and complexity of code are really big and everything beyond this error work as it should.
    – NickName43
    May 26, 2020 at 9:38

1 Answer 1


To clean up the old data:

Map<String, Object__c> records = new Map<String, Object__c>();
Object__c[] dupes = new Object__c[0];
for(Object__c record: [SELECT Name FROM Object__c]) {
  // put returns old record from map, if any
  Object__c temp = records.put(record.Name, record);
  // so this is a duplicate
  if(temp != null) {
delete dupes;

To prevent this problem in the future:

Object__c[] records = new Object__c[0];
for(Object value: listOfValues) {
  records.add(new Object__c(Name=...));
upsert records Object__c.Name;

Using upsert by name will automatically deduplicate records. This won't work if you already have duplicates in the system, but you can use this to save queries and automatically prevent duplicates.

Not the answer you're looking for? Browse other questions tagged .