function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dilip KulkarniDilip Kulkarni 

trigger( prevent duplicates) on account object.

Hi Experts,
I need to create a trigger on account object which will prevent the users in creating duplicate account based on the name.
Kindly provide me the same.

Regards.
Best Answer chosen by Dilip Kulkarni
Dayakar.DDayakar.D
Update previus trigger with the following 
trigger AccountDuplicateTrigger on Account (before insert,before update) {
    list<string> accountNames=new list<string>();
    for(Account accountVar:trigger.new)
    {
        accountNames.add(accountVar.name);
    }
    list<Account> listOfDuplicateAccounts=[select id,name from Account where name in :accountNames];
    for(Account account:trigger.new)
    {
        if(trigger.isInsert){
        if(listOfDuplicateAccounts.size()!=0)
        {
            account.addError('Account already exists with this name');
        }
        }
        if(trigger.isUpdate)
        {
           for(Account oldaccount :trigger.old)
           {
               if(account.Name!=oldAccount.Name && listOfDuplicateAccounts.size()!=0)
               {
                   account.addError('Account already exists with this name');
               }
           }
        }
    }
    

}

BestRegards,
Dayakar.D

All Answers

Dayakar.DDayakar.D
Hi Dilip Kulkarni,

Please try below trigger.
trigger AccountDuplicateTrigger on Account (before insert) {
    list<string> accountNames=new list<string>();
    for(Account accountVar:trigger.new)
    {
        accountNames.add(accountVar.name);
    }
   //getting list of accounts with given name
    list<Account> listOfDuplicateAccounts=[select id,name from Account where name in :accountNames];
    for(Account account:trigger.new)
    {
        if(listOfDuplicateAccounts.size()!=0)
        {
            account.addError('Account already exists with this name');
        }
    }

}

Please let me know if it works.

BestRegards,
Dayakar.D
 
Dilip KulkarniDilip Kulkarni
Thanks Dayakar. I will check and revert.
Deepak Maheshwari 7Deepak Maheshwari 7
trigger AccountDuplicateTrigger on Account (before insert,before update) {

    
     map<Id,Account> existingAccountMap = new  map<Id,Account>([Select Id, Name From Account Where Name != null]); 

     for(Account a : Trigger.new){
        if(a.name = existingAccountMap.get(a.Id).Name ){
          a.adderror('You cannot create a dulplicate account');
        }
     }
}

Hope this will help you!
Dilip KulkarniDilip Kulkarni
Deepak,I will try. Thnaks
Dilip KulkarniDilip Kulkarni
 Hi Dayakar,
Your trigger works fine. Can I put (before insert,before update) for the same?
 
Dilip KulkarniDilip Kulkarni
Hi Deepak,
Your trigger is giving message on account as:

Apex trigger AccountDuplicateTrigger caused an unexpected exception, contact your administrator: AccountDuplicateTrigger: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.AccountDuplicateTrigger: line 13, column 1.

Instead of 'You cannot create a dulplicate account'.
Dayakar.DDayakar.D
Update previus trigger with the following 
trigger AccountDuplicateTrigger on Account (before insert,before update) {
    list<string> accountNames=new list<string>();
    for(Account accountVar:trigger.new)
    {
        accountNames.add(accountVar.name);
    }
    list<Account> listOfDuplicateAccounts=[select id,name from Account where name in :accountNames];
    for(Account account:trigger.new)
    {
        if(trigger.isInsert){
        if(listOfDuplicateAccounts.size()!=0)
        {
            account.addError('Account already exists with this name');
        }
        }
        if(trigger.isUpdate)
        {
           for(Account oldaccount :trigger.old)
           {
               if(account.Name!=oldAccount.Name && listOfDuplicateAccounts.size()!=0)
               {
                   account.addError('Account already exists with this name');
               }
           }
        }
    }
    

}

BestRegards,
Dayakar.D
This was selected as the best answer
Dilip KulkarniDilip Kulkarni
Hi Dayakar,
Thank you very much. Could you please elaborate me the logic in this trigger in detail,as I am new to apex coding.
Dayakar.DDayakar.D
Hi Dilip,
Please find code comments,
trigger AccountDuplicateTrigger on Account (before insert,before update) {
    list<string> accountNames=new list<string>();
    for(Account accountVar:trigger.new)
    {
        accountNames.add(accountVar.name);
    }
    //getting list of accounts with givien name
    list<Account> listOfDuplicateAccounts=[select id,name from Account where name in :accountNames];
    for(Account account:trigger.new)
    {
        /*here we are checking is it insert event or not
         * if insert event then returns true else returns false
         * */
        if(trigger.isInsert){
            /*here we are checking dulicate account list size 
             * if size is 0 it means no duplicate accounts
             * */
        if(listOfDuplicateAccounts.size()!=0)
        {
            account.addError('Account already exists with this name');
        }
        }
        /*here we are checking is it update event or not
         * if update event then returns true else returns false
         * */
        if(trigger.isUpdate)
        {
           for(Account oldaccount :trigger.old)
           {
               /*when updating an account we are checking that account name is changed or not
                * Here account.Name is new value provided and oldAccount.Name name represents old name of account
                * if name is changed then we are checking given account name is already existing or not
                **/
               if(account.Name!=oldAccount.Name && listOfDuplicateAccounts.size()!=0)
               {
                   account.addError('Account already exists with this name');
               }
           }
        }
    }
    

}
BestRegards,
Dayakar.D
Dilip KulkarniDilip Kulkarni
Thanks Dayakar for the elaboration. If anything further required, I will let you know.
Dilip KulkarniDilip Kulkarni
Hi Dayakar,
What will be the test class for the trigger below:

trigger AccountDuplicateTrigger on Account (before insert) {
    list<string> accountNames=new list<string>();
       for(Account accountVar:trigger.new)
     {
         accountNames.add(accountVar.name);
     }
     //getting list of accounts with given name
     list<Account> listOfDuplicateAccounts=[select id,name from Account where name in:accountNames];
     for(Account account:trigger.new)
     {
        if(listOfDuplicateAccounts.size()!=0)
        {
            account.addError('Account already exists with this name');
        }
    }
 
   }
Dayakar.DDayakar.D
Hello Dilip,

Here is test class for the trigger.
@isTest
public class AccountDuplicateTriggerTestClass {
  Static testMethod Void AccountDuplicatePreventer()
   {
      Boolean result = false;
      Account firstAcc = new Account(Name='xyz');
      insert firstAcc;
       Account secondAcc=New Account(Name='Test');
       insert secondAcc;
      try{
           Account duplicateAcc = new Account(Name='xyz');
           insert duplicateAcc;
       }catch(DmlException ex){ result = true;}
      System.assert(result);
       try{
           firstAcc.Name='Test';
           Update firstAcc;
       }catch(DmlException ex){ result = true;}
      System.assert(result);
   }
}

Please let me know, if you have any issues.

BestRegards,
Dayakar.D
Dilip KulkarniDilip Kulkarni
Thank you. I will let you know the code coverage.
Dilip KulkarniDilip Kulkarni
Hi Dayakar,
I got 100% code coverage.Thanks for your kind help.
Hariharan ramyaHariharan ramya
Preventing the users to create Duplicate Accounts  (Based on the Account Name )

Sample Code :

trigger AccountDuplicateTrigger on Account (before insert,before update) {
   
    for(Account a:Trigger.new)
    {
        List<Account> acc=[select ID from account where Name=:a.Name ];
        if(acc.size()>0)
        {
            a.name.adderror('You cannot create a dulplicate account');
        }
    }
}
raj_sfdccraj_sfdcc
Hi ,
Below post can be used to avoid Duplicate Fields by using trigger :

Here i have used Author object and Email field for my requirement .Please use your Sobject and field according to your requirement in the place of Email
trigger DemoTrigger on Author__c (before insert,before update) {
    List<Author__c> accList=new List<Author__c>([select Author_Email__c from Author__c]);
    map<String,Author__c> accmap=new map<String,Author__c>();
    for(Author__c acc:accList){
        accmap.put(acc.Author_Email__c,acc);
    }
 
    if(Trigger.isinsert&&Trigger.isbefore){
        for(Author__c acc:Trigger.new){
            if(accmap.get(acc.Author_Email__c)!=null){
                acc.adderror('Email already exists');
            }
        }
    }
}


Please find the below post further information:

Avoid Duplicate for Insert Operation By Using Apex Trigger  (https://salessforcehacks.blogspot.com/2019/12/avoid-duplicate-fields-using-apex.html)

And the below Post explaines how to avoid Duplicate Fields by updating the above code :

Avoid Duplicates for both insert and Update Operation  (https://salessforcehacks.blogspot.com/2019/12/avoid-duplicate-fields-using-apex_21.html)

I have created insert and update operation seperately  to make you understand Clearly.

Please let me know if you require any further information
raj_sfdccraj_sfdcc
Hi Dilip,

Please find the below post ,Which explains more about avoiding duplicate records .

Duplicate Records (https://salessforcehacks.blogspot.com/2019/12/avoid-duplicate-fields-using-apex_21.html)

Please make use of below post for more hands on examples of apex trigger .
Apex Trigger Examples (https://salessforcehacks.blogspot.com/2020/02/apex-trigger-examples-salesforce-apex.html)
smriti sharan19smriti sharan19
trigger AccountDuplicateCheckTrigger on Account (before insert) {
       //Preparing Account names in Set from trigger.new

        Set<String> nameSet = new Set<String>();

        for(Account acc : trigger.new){

            nameSet.add(acc.name);        

        }

        // getting the list of accounts in database  with the account name we entered ( trigger.new)
        
        List<Account> accList = new List<Account>([select id,name from Account where name in: nameSet]);

        for(Account a : trigger.new){

            if(accList.size() > 0 )
                a.addError('Account already exists in your Organization with name '+a.name);

        }

}
Soumendu Sarkar 5Soumendu Sarkar 5
// following trigger can prevent duplicate values inserting into account object but it if trigger.New has duplicate records in it but not present in account object it will add all the duplicate. 

trigger AccountTrigger on Account (before insert) {
If(trigger.isInsert && trigger.IsBefore){
    Set<string> AccNames = new Set<string>();
    for( account acc : trigger.new){
            AccNames.Add(acc.Name);
    }
    List<account> DuplicateAccounts = [Select id,Name from Account where Name In :AccNames ];
    If (DuplicateAccounts.size()>0)
    {
        for( account acc : trigger.new){
            for(account dupAcc:DuplicateAccounts){
            if(acc.name== dupAcc.Name && acc.Name!=null){
                acc.Name.addError('Error: Record already exist with the name -'+acc.name);
            }
            }
    }
    }
}
}