+ Start a Discussion
suresh dupadasuresh dupada 

How to Check Duplicate email in the trigger while insert and update

How to write trigger to avoid duplicate email when bulkfying the trigger

my trigger is:

trigger AvoidDuplicate on contact (before insert,before update)
{
   if(Trigger.isInsert||Trigger.isUpdate)
      for(contact a:trigger.new)
     {
         integer count=[select count from contact where email=:a.email];
         if(count>0)
          {
                 a.Email.adderror('This email already exists');
          }
     }
}

this is working fine when inserting single records

but it shows error when working with dataloader...... Please help to to over come this error


I would appriciate for any kind of replay...............
Best Answer chosen by suresh dupada
Bhanu MaheshBhanu Mahesh
Hi Suresh,

Try below code
trigger contactDuplicatePreventer on Contact
                               (before insert, before update) {

    Map<String, Contact> contactMap = new Map<String, Contact>();
    for (Contact Contact : System.Trigger.new) {
		
        // Make sure we don't treat an email address that  
        // isn't changing during an update as a duplicate.  
    
        if ((Contact.Email != null) &&
                (System.Trigger.isInsert ||
                (Contact.Email != 
                    System.Trigger.oldMap.get(Contact.Id).Email))) {
		
            // Make sure another new Contact isn't also a duplicate  
    
            if (contactMap.containsKey(Contact.Email)) {
                Contact.Email.addError('Another new Contact has the '
                                    + 'same email address.');
            } else {
                contactMap.put(Contact.Email, Contact);
            }
       }
    }
	
    // Using a single database query, find all the Contacts in  
    
    // the database that have the same email address as any  
    
    // of the Contacts being inserted or updated.  
    
    for (Contact contact : [SELECT Email FROM Contact
                      WHERE Email IN :contactMap.KeySet()]) {
        Contact newContact = contactMap.get(Contact.Email);
        newContact.Email.addError('A Contact with this email '
                               + 'address already exists.');
    }
}

Check the below link for your reference
http://developer.force.com/cookbook/recipe/preventing-duplicate-records-from-saving

Regards,
Bhanu Mahesh

All Answers

Bhanu MaheshBhanu Mahesh
Hi Suresh,

Try below code
trigger contactDuplicatePreventer on Contact
                               (before insert, before update) {

    Map<String, Contact> contactMap = new Map<String, Contact>();
    for (Contact Contact : System.Trigger.new) {
		
        // Make sure we don't treat an email address that  
        // isn't changing during an update as a duplicate.  
    
        if ((Contact.Email != null) &&
                (System.Trigger.isInsert ||
                (Contact.Email != 
                    System.Trigger.oldMap.get(Contact.Id).Email))) {
		
            // Make sure another new Contact isn't also a duplicate  
    
            if (contactMap.containsKey(Contact.Email)) {
                Contact.Email.addError('Another new Contact has the '
                                    + 'same email address.');
            } else {
                contactMap.put(Contact.Email, Contact);
            }
       }
    }
	
    // Using a single database query, find all the Contacts in  
    
    // the database that have the same email address as any  
    
    // of the Contacts being inserted or updated.  
    
    for (Contact contact : [SELECT Email FROM Contact
                      WHERE Email IN :contactMap.KeySet()]) {
        Contact newContact = contactMap.get(Contact.Email);
        newContact.Email.addError('A Contact with this email '
                               + 'address already exists.');
    }
}

Check the below link for your reference
http://developer.force.com/cookbook/recipe/preventing-duplicate-records-from-saving

Regards,
Bhanu Mahesh
This was selected as the best answer
Himanshu ParasharHimanshu Parashar
Hi Suresh,

First of all your code is not bulkfied it will throw Too Many SOQL error if bulk uploading happen,

Here is the correct code.
 
trigger AvoidDuplicate on contact (before insert,before update)
{
   set<String> setEmail = new set<String>();
   set<String> setExistingEmail = new set<String>();

   //Add alll email in set to fetch related existing records
   for(Contact con : Trigger.new)
   {
          setEmail.add(con.email);

    }

   // get all records in database.
    for(Contact con : [select email from contact where email in : setEmail)
   {
          setExistingEmail.add(con.email);
    }

   //compare and add error if already exist
   if(Trigger.isInsert||Trigger.isUpdate)
     for(contact a:trigger.new)
     {
         if(setExistingEmails.contains(a.email))
        {
                 a.Email.adderror('This email already exists');
          }
     }
}


Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S.  If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
 
Vj AryaVj Arya
Hi Himanshu, 

I used your code, but found a bug while finding duplicates record on base of Email in the imported batch, i.e. If imported batch have duplicate email  itself it doesn't handle that.

Here is an updated code for the same: 

trigger DuplicateEmailsInContacts on Contact (before insert, before update){
    Set<String> EmailSet = new set<String>();
    Set<String> ExistingEmailSet = new set<string>();
 
    for(Contact c : Trigger.New){
        IF(c.Email != '' && c.Email != NULL){
            If(!EmailSet.contains(c.Email)){
                EmailSet.add(c.Email);
            }
        }
    }
    
    //Updating ExistingEmailSet
    for(Contact con : [SELECT Email From Contact where Email IN :EmailSet]){
        ExistingEmailSet.add(con.Email);
    }
    
    IF(Trigger.IsInsert || Trigger.IsUpdate){
        for(Contact c1 : Trigger.New){
            System.Debug(ExistingEmailSet);
            IF(ExistingEmailSet.contains(c1.Email)){
                c1.Email.addError('Email Already Exists : '+c1.Email);
            }else if(c1.Email != null || c1.Email != ''){
                ExistingEmailSet.add(c1.Email);
            }
        }
    }
    
}

 
Rajesh-SFDCRajesh-SFDC
I tried suresh code it is working fine i used data import wizard for loading and it is working fine 
ashu 6112ashu 6112
trigger AvoidDuplicate on contact (before insert,before update){
    List<String> lstEmail = new List<String>();
        for(contact con:trigger.new){
            lstEmail.add(con.Email);
            }
        List<Contact> lstContact=[select id from contact where email IN :lstEmail];
         
        if(lstContact.size() > 0){
            con.Email.adderror('This email already exists');
            }
}
Priya 777Priya 777
Hi For this trigger will it be possible it through following way .please let me know  

Suppose i have alredy existing User contact with Email address xyz@gmail.com which is active 
If i try to create the 2 nd User with same email address xyz@gmail.com it will through error that email already exists because the first user  is active.

I want to make my trigger to work like if  xyz@gmail.com(1st user) is inactive for first user it should allow me to use the same email address for creating the second user with xyz@gmail.com.