In Salesforce, Contacts are usually linked to Accounts meaning each contact works under a specific company or customer record. But what if you want to verify whether a specific Contact belongs to a specific Account?
In this blog post, we’ll write a simple Apex method that:
Accepts an Account name and a Contact name.
Checks if the Contact exists under that Account.
Returns
true
if the relationship exists, orfalse
if it doesn’t.
This kind of logic is perfect for validation checks, automation, or even when integrating with external systems where you need to verify parent-child relationships.
Let’s break it down in a beginner-friendly way!
🧠 What Are We Trying to Do?
Imagine you have:
An Account called “Acme Inc”
A Contact named “John Doe”
Now you want to know does John Doe work for Acme Inc in your Salesforce org?
Instead of clicking around manually, we’ll write an Apex method to check it for us and return true
or false
based on what it finds.
🔍 Code Explanation
public with sharing class ApexUseCaseFive {
public static Boolean checkIfCombinationExists(String accountName, String contactName){
We define a class named ApexUseCaseFive
, and inside it, we create a static method named checkIfCombinationExists
. It takes two input parameters:
accountName
: the name of the AccountcontactName
: the name of the Contact
List<Contact> conRecords = [SELECT id FROM Contact WHERE Name = :contactName AND Account.Name = :accountName];
We use a SOQL query to fetch Contacts where:
The Contact’s Name matches the input
AND the Account’s Name also matches
This uses a relationship query (Account.Name
) to check the parent object (Account) from the child object (Contact).
if(conRecords.size() > 0){
return true;
}
If the query returns at least one record, it means a matching Account–Contact pair exists, so we return true
.
return false;
}
}
If the list is empty, we return false
, meaning the combination doesn’t exist.
✅ Why This Is Useful
This is a simple but very useful utility method for:
Validating input before creating new records
Preventing duplicates or incorrect associations
Ensuring data accuracy in your Apex logic
Confirming relationships before triggering actions like emails or tasks
It’s a great example of combining SOQL with logical checks in Apex.
🧾 Final Code Snippet
public with sharing class ApexUseCaseFive {
public static Boolean checkIfCombinationExists(String accountName, String contactName){
List<Contact> conRecords = [SELECT id FROM Contact WHERE Name = :contactName AND Account.Name = :accountName];
if(conRecords.size() > 0){
return true;
}
return false;
}
}
🎥 Watch It in Action!
Prefer seeing it done in real time? Here’s a short demo showing how this method works inside Salesforce.