1

I'm writing a trigger that needs to create a record based on a newly inserted one. The trigger I have now works, but only for small amounts of records. The problem is where I need to check if there is already an Account with the same FirstName, LastName and PersonEmail as the inserted one. Currently I just query all accounts for any matching all three fields, but obviously this results in a lot of SOQL queries when the trigger is called with lots of new objects. Is there a way to remove the need for so many SOQL queries?

  • Did you manage to resolve your issue? – Alex Tennant Sep 25 '14 at 8:24
2

Rather than performing the query for each record that comes into your trigger - which is what it sounds like you're doing. What you need to do is perform 1 much broader query that gets back all of the likely candidates for duplicate records. Then do the duplicate processing in Apex using a composite key.

For example:

// Build up your query clauses
Set<String> firstNames = new Set<String>();
Set<String> lastNames = new Set<String>();
Set<String> emails = new Set<String>();

for(Contact c : Trigger.new)
{
    firstNames.add(c.FirstName);
    lastNames.add(c.LastName);
    emails.add(c.Email);
}

// Get all potential duplicates
List<Contact> potentialDuplicates = 
[
    SELECT Id ... 
    FROM Contact 
    WHERE 
        FirstName IN :firstNames 
        AND LastName IN :lastNames 
        AND Email IN :emails
];

// Create a map based on a composite key
Map<String, Contact> duplicateMap = new Map<String, Contact>();

for(Contact c : potentialDuplcaites)
{
    String key = c.FirstName + c.LastName + c.Email;
    duplicateMap.put(key, c);
}

// Look for duplicates
for(Contact c : Trigger.new)
{
    String key = c.FirstName + c.LastName + c.Email;
    Contact duplicate = duplicateMap.get(key);

    if(duplicate != null)
    {
        // Record is a duplicate, so whatever you need to do
    }
}
-1

Try to include more filters to the query like record type check etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.