Working with Contacts in Salesforce often means dealing with Account relationships. One common scenario is when you want to check if two Contact records belong to the same Account basically, asking the question:
“Do these two people work for the same company?”
This is a practical and frequently-used logic in the real world for example, when you’re:
Grouping contacts under an account
Matching people to companies
Checking relationship hierarchies
Avoiding duplicate communications
In this blog post, we’ll go over how to write a simple Apex method that accepts two Contact records and returns true
if they share the same Account ID, and false
otherwise.
🧠 What Are We Trying to Do?
Here’s what our method should accomplish:
Accept two
Contact
records as input.Check if both records are not null.
Ensure both Contacts have an associated
AccountId
.If they do, compare the Account IDs.
If the Account IDs are the same → return
true
.If they’re different or missing → return
false
.
That’s it — and it’s super useful when you’re dealing with relationship-based logic.
🔍 Code Explanation
public with sharing class ApexUseCaseTwentyTwo {
public static Boolean checkIfConHasSameParents(Contact conRecord1, Contact conRecord2){
We define a new Apex class named ApexUseCaseTwentyTwo
. Inside it, we create a static method that takes two Contact records as parameters.
if(conRecord1 != null && conRecord2 != null){
Before doing anything, we check that neither of the input Contact records is null.
if(conRecord1.AccountId != null && conRecord2.AccountId != null){
Next, we ensure both Contact records are linked to an Account since AccountId
could be null if the Contact isn’t associated with any company.
if(conRecord1.AccountId == conRecord2.AccountId){
return true;
}
}
}
return false;
}
}
If the Account IDs match, that means both Contacts belong to the same Account, so we return true
. Otherwise, we return false
.
This method is safe, readable, and works well for basic comparison use cases.
✅ Why This Is Useful
You can use this method in many practical scenarios:
In custom validation rules (e.g., avoid duplicate contacts under the same account)
When building UI logic to display related contacts
For reporting or automation where relationships matter
And the great part? You can extend this to other objects too like comparing Opportunities under the same Account, or Cases linked to the same Contact.
🧾 Final Code Snippet
public with sharing class ApexUseCaseTwentyTwo {
public static Boolean checkIfConHasSameParents(Contact conRecord1, Contact conRecord2){
if(conRecord1 != null && conRecord2 != null){
if(conRecord1.AccountId != null && conRecord2.AccountId != null){
if(conRecord1.AccountId == conRecord2.AccountId){
return true;
}
}
}
return false;
}
}
🎥 Watch It in Action!
Want a quick visual demo of how this logic works? Watch the short YouTube video where I test two Contact records and compare their Account relationships.