Let’s say you’re working with Leads in Salesforce and want to avoid entering the same person twice maybe someone filled out your form twice or someone on your team accidentally added a lead that already exists.
In this post, we’ll walk through how to write a simple duplicate checker method using Apex that compares a new or existing Lead record with others in the system and determines whether a duplicate already exists based on key fields like name, email, lead source, and industry.
This is especially useful for keeping your CRM data clean and preventing clutter or confusion caused by duplicate records.
🧠 What Are We Trying to Do?
We want a method that:
Accepts a
Lead
record as input (either new or existing)Searches the Lead object for other records with the same:
Name
Email
Lead Source
Industry
Ignores the current Lead record (to avoid matching with itself)
Returns
true
if a duplicate exists, andfalse
otherwise
This is a very practical utility method for any sales or marketing team!
🔍 Code Explanation
public with sharing class ApexUseCaseTwentyOne {
public static Boolean checkLeadDuplicates(Lead leadRecToCheck){
We define a class called ApexUseCaseTwentyOne
with a method checkLeadDuplicates
that accepts one Lead
record as a parameter.
if(leadRecToCheck != null){
First, we check that the input record isn’t null (just to be safe).
List<Lead> leadRecords = [SELECT Id FROM Lead
WHERE Id != :leadRecToCheck.Id
AND Name = :leadRecToCheck.Name
AND Email = :leadRecToCheck.Email
AND LeadSource = :leadRecToCheck.LeadSource
AND Industry = :leadRecToCheck.Industry];
We then run a SOQL query on the Lead object to find any other Lead records with the same values for name, email, lead source, and industry but with a different ID (to skip comparing it with itself).
if(leadRecords.size() > 0){
return true;
}
}
return false;
}
}
If the query returns one or more records, that means a duplicate exists, so we return true
. Otherwise, we return false
.
✅ Why This Is Useful
This method helps you:
Avoid duplicate records from manual entry or integration
Build custom validation logic in triggers or flows
Maintain clean and reliable CRM data
You could even expand this logic to:
Check for duplicates on phone number or company
Include fuzzy matching (like Levenshtein distance for names)
Trigger warnings or block saves based on this result
🧾 Final Code Snippet
public with sharing class ApexUseCaseTwentyOne {
public static Boolean checkLeadDuplicates(Lead leadRecToCheck){
if(leadRecToCheck != null){
List<Lead> leadRecords = [SELECT Id FROM Lead
WHERE Id != :leadRecToCheck.Id
AND Name = :leadRecToCheck.Name
AND Email = :leadRecToCheck.Email
AND LeadSource = :leadRecToCheck.LeadSource
AND Industry = :leadRecToCheck.Industry];
if(leadRecords.size() > 0){
return true;
}
}
return false;
}
}
🎥 Watch It in Action!
Want to see how it works in real time? Watch my short demo video where I create a test lead and check for duplicates using this method.