Having duplicate records in your salesforce org can cause serious issue not limited to inaccurate reporting and lost opportunities. It’s crucial to identify and remove them for business-critical reasons. In this post, we will see how to find duplicate records.
Using SOQL to find duplicate records
Simple and easiest way to find duplicate records in salesforce is to use SOQL. You would typically want to identify records that have identical values in one or more fields in records. For example, you’re tasked to find duplicate Contact by its Phone number.
So in this case you can use GROUP BY clause of SOQL. This clause can be used to aggregate records by specific fields, and you can then use the HAVING clause to filter out groups that contain only one record, leaving you with those that have duplicates. Let’s in practice for above Lead example,
SELECT Phone, Count(Id) FROM Contact GROUP BY Phone HAVING Count(Id)>1
First part of query from Line 1 to 3, It will Select Phone field and counts the number of contact records for each of phone numbers.
now second part line 4, using HAVING clause along with group by you can filter all aggregated records so here filter Count(Id)>1, will give you all records where phone numbers occurs more than once among all records.
Read more on use of Group by in SOQL Here
Few more Examples
1. Find duplicate leads by its Name and LeadSource
SELECT Name, LeadSource Count(Id) FROM Lead GROUP BY Name, LeadSource HAVING Count(Id)>1
This will give you number of lead records for each duplicated Name and LeadSource.
2. Find duplicate Opportunities by Name and AccountId
SELECT Name, AccountId Count(Id) FROM Opportunity GROUP BY Name, AccountId HAVING Count(Id)>1
This will give you number of opportunity records for each duplicated Name and its Account.
Conclusion
Using these SOQL queries with GROUP BY & HAVING clause, you can easily find duplicate records in Salesforce based on fields like Name, Email, AccountId, and custom fields. Identifying duplicates is the first step toward maintaining clean, accurate data in your Salesforce environment.




