Find duplicate records using SOQL Query

Hi guys, As you already know Salesforce has provided declarative tools like “Duplicate Rule” and “Machining Rule”. Which is prevent from duplicate records. But but but, You know these all tools work on new records.

So, What about old records. How you will find duplicates.

In this article, I am sharing a short apex code. To find the duplicate record from old records.

Apex Code:-

Set<String> setOfDuplicateNames = new Set<String>();
for (AggregateResult aggregate : [SELECT Name,count(id),AccountNumber FROM Account GROUP BY Name,AccountNumber HAVING count(Name)>1])
{
setOfDuplicateNames.add((String)aggregate.get('Name'));
}
for (Account account : [
SELECT Name, AccountNumber
FROM Account
WHERE Name IN :setOfDuplicateNames
]){
system.debug('==>Name '+account.Name);
}

Hope above code will solve your problem. Please share it if you found it valuable.

You can comment below, If you have any queries related above topic. Subscribe our blog for the latest updates.

Follow us on twitter and join our WhatsApp group.