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
Sonam PatilSonam Patil 

trigger to prevent duplicate trigger.

Hi,
Below is my code for the trigger for  duplicate prevention on the account . It works well, but if I have 50k records this impacts scalability and not feasible.
So please any one can help to code in better way.
thanks in advance.
trigger AccountDuplicate on Account (before insert) {
 List<Account> dup = new List<Account>();
 dup = [Select id, Name from Account];
 for(Account a:Trigger.New){
 for(Account a1:dup){
 if(a.Name==a1.Name){
 a.Name.addError('Name already Exist ');
 }
 }
 }   
 }
Best Answer chosen by Sonam Patil
Amit Chaudhary 8Amit Chaudhary 8
Never use Soql without any filter or limit. Once account count will inc your code will fail

Please try below code.
trigger AccountDuplicate on Account (before insert)
{

	Set<String> setName = new Set<String>();
	For(Account acc : trigger.new)
	{
		setName.add(acc.name);
	}
	
	if(setName.size() > 0 )
	{
		List<Account> lstAccount = [select name ,id from account where name in :setName ];
		
		Map<String ,Account> mapNameWiseAccount = new Map<String,Account>();
		For(Account acc: lstAccount)
		{
			mapNameWiseAccount.put(acc.name ,acc);
		}
		
		For(Account acc : trigger.new)
		{
			if(mapNameWiseAccount.containsKey(acc.name))
			{
				acc.Name.addError('Name already Exist ');
			}
		}
		
	}
}

Please check below post for trigger. I hope that will help you
1) http://amitsalesforce.blogspot.com/search/label/Trigger
2) http://amitsalesforce.blogspot.com/2015/06/trigger-best-practices-sample-trigger.html

Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers


4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail

All Answers

GauravGargGauravGarg

Hi Sonam,
 

Please try below code:

trigger AccountDuplicate on Account (before insert) {
	 Map<Id,Account> duplicateMap = new Map<Id,Account>([Select id, Name from Account]);
	 for(Account a:Trigger.New){
		if(duplicateMap.containsKey(a.Name)){
			a.Name.addError('Name already Exist ');
		}
	 }   
 }
If you found error in above code, try below one:
 
trigger AccountDuplicate on Account (before insert) {
	 Map<Id,Account> duplicateMap = new Map<Id,Account>();
	 duplicateMap = [Select id, Name from Account];
	 for(Account a:Trigger.New){
		if(duplicateMap.containsKey(a.Name)){
			a.Name.addError('Name already Exist ');
		}
	 }   
 }



Let me know if you face any issues. 

Thanks,

Gaurav
Email: gauravgarg.nmim@gmail.com

Amit Chaudhary 8Amit Chaudhary 8
Never use Soql without any filter or limit. Once account count will inc your code will fail

Please try below code.
trigger AccountDuplicate on Account (before insert)
{

	Set<String> setName = new Set<String>();
	For(Account acc : trigger.new)
	{
		setName.add(acc.name);
	}
	
	if(setName.size() > 0 )
	{
		List<Account> lstAccount = [select name ,id from account where name in :setName ];
		
		Map<String ,Account> mapNameWiseAccount = new Map<String,Account>();
		For(Account acc: lstAccount)
		{
			mapNameWiseAccount.put(acc.name ,acc);
		}
		
		For(Account acc : trigger.new)
		{
			if(mapNameWiseAccount.containsKey(acc.name))
			{
				acc.Name.addError('Name already Exist ');
			}
		}
		
	}
}

Please check below post for trigger. I hope that will help you
1) http://amitsalesforce.blogspot.com/search/label/Trigger
2) http://amitsalesforce.blogspot.com/2015/06/trigger-best-practices-sample-trigger.html

Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers


4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail
This was selected as the best answer
Patil Manjunath 3Patil Manjunath 3
trigger Accountinsert on Account (before insert) {
    for(Account a:Trigger.New){
       List<Account> mynew=[Select id,name from Account where name=:a.name];
        If(mynew.size()>0) {
            a.Name.addError('Account with name is existing');
        }
            
        }
        
    }

 
suresh avsuresh av
trigger duplacate on Account (before insert) { 
    Set<String> setName = new Set<String>();   
    Map<String,Integer> accnamesVsCount = new Map<String,Integer>();
    For(Account acc : trigger.new)        
    {      
        if(accnamesVsCount.containsKey(acc.Name))
            acc.addError('Account Name is already exists');
        else
            accnamesVsCount.put(acc.Name,1);
        setName.add(acc.name);
    }
    if(setName.size() > 0 )
     {        
        List<Account> lstAccount = [select name ,id from account where name in :setName ];
        Map<String ,Account> mapNameWiseAccount = new Map<String,Account>();        
        For(Account acc: lstAccount)            
        {            
            mapNameWiseAccount.put(acc.name ,acc);            
        }
         
         system.debug(mapNameWiseAccount.size());
        For(Account acc : trigger.new)            
        {            
            if(mapNameWiseAccount.containsKey(acc.name))
            {
                acc.Name.addError('Name already Exist ');
            }
         }
        }
    }

//open execute anonymouse window

list<Account>  acc=new list<account>();
for(integer i=0;i<10;i++)
{if(i<3){acc.add(new account(name='sam1'));}else{acc.add(new account(name='ram'));}
    
}
System.debug('list'+acc );
    database.insert(acc,false);
arti rathodarti rathod
@Amit Chaudhary 8 
why u did use list n set if we can do through map....could u plz explain me.
raj_sfdccraj_sfdcc
Hi ,
Below post can be used to avoid Duplicate Fields by using trigger :

@ arti rathod I have used Map in the below code
 
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 to make you understand Clearly.
ashu 6112ashu 6112
Hi @amit ,

Godd explaination by you , but am having one concern how your code will check duplicacy within the data itself that are coming in bulk, it will compare with existing data only, not among the incoming data stored in Trigger.new
GauravGargGauravGarg

@Ashu, 

if you want to check the duplicate records within salesforce without making an additional query in the apex class.
1. Always use Upsert call instead of Insert call. It will automatically check the duplicates i.e. link with existing data or create new. 
2. Create duplicate-matching rules. 

I hope this will help you, let me know if you still need any help or you can contact me on the below details.

Thanks,
Gaurav
Email: gauravgarg.nmims@gmail.com

Arvind_SinghArvind_Singh
Below Solution will work for bulk upload and Account insert using UI - 
 
trigger Account_trigger on Account (before insert) {
    map<string,Account> nameMap = new Map<String,Account> ();
    List<string> accountNameList = new List<String> ();
    for(Account ac : trigger.new) {
        accountNameList.add(ac.Name);
        nameMap.put(ac.Name, ac);
    }
    List<Account> actList = [Select Id,name from Account where name=:accountNameList];
    if(ActList.size() > 0) {
        for(Account a : trigger.new) {
            if(nameMap.containsKey(a.Name)) {
                a.adderror('Error - Duplicate Account !! Account name '+ a.Name +' alreay present in system');
            }
        }
    }
}

 
Shiva SrkShiva Srk

Code to check for Duplicate Account using Map.
trigger AccountTrigger on Account (before insert, before update) {
    
    List<Account> accObj = [Select id, Name from Account]; 
    Map<string,Account> accMap = new  Map<string,Account>();
    
    for(Account ac : accObj){
        accMap.put(ac.Name, ac);
    }
    
    for(Account acc: Trigger.New){
        if(accMap.containsKey(acc.Name)){
            acc.addError('Duplicate Record Found'); 
        }
        
    } 
}


 
Anand ManhasAnand Manhas
@ashu6112 I think that's the reason he used a set to store all the names of the accounts in the beginning so that the duplicates are removed in the initial step.
NIKHIL KUMAR 236NIKHIL KUMAR 236

@GauravGarg   pls learn some programminng  and post here.  You are searching name in the id field.
NIKHIL KUMAR 236NIKHIL KUMAR 236
@arvind_Singh  you are adding name in the map from trigger.new   , and then searching the map from trigger.new  .  pls dont post misleading programs . Don't post if u r a noob .
Sachin LightningSachin Lightning
Please add for undelete also
Hemant Kumar 145Hemant Kumar 145
Hi,
Can someone post a fresh bulkified code for Duplicate Account list.
Thanks in advance
Butesh SinglaButesh Singla
Hi,
follow this link Trigger to prevent creating duplicate accounts in salesforce (https://lovesalesforceyes.blogspot.com/2020/05/triggger-to-prevent-duplicate-accounts.html)
Dinesh Baddawar 3Dinesh Baddawar 3
this trigger stops from inserting duplicate account record

trigger DuplicateAccount on Account (before insert) {
     
    for(Account acc:trigger.new){
        List<Account> acclist=[Select id,name From Account Where Name =:acc.name];
        if(acclist.size()>0){
            acc.name.addError('Account Already Exist');
        }
    }
  }
Dinesh Baddawar 3Dinesh Baddawar 3
this is also a trigger for stopping duplicate contact records but is before the update and before insert.


trigger DuplicateContact on Contact (before insert,before update) {

    for(Contact con:trigger.new){
        List<Contact> conlist=[Select id ,lastname From Contact Where lastname =:con.lastname];
        if(conlist.size()>0){
            con.lastname.addError('Contact Already Exist');
        }
    }  
}
satyajit shitolesatyajit shitole
@Dinesh Baddawar 3 you are using SOQL query in for loop which is not BEST PRACTICES.
salluri sureshsalluri suresh
trigger AccountDuplicateCheckTrigger on Account (before insert)
{

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

for(Account acc : trigger.new)
{
nameSet.add(acc.name);
}

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);
}
}
Vishal ThubeVishal Thube
Hi,
Below is my code for the trigger for prevention duplicate Name in the account . 
1.Best Code & Small  
2.Flexible 
3.Bulkify 
4.scalability

Try it once.... n hit like if u like it




trigger PreventDuplicateAccName on Account (before insert,before Update ){
    Set <string> accSet = new Set <String>();
        
    for (Account objAcc : trigger.new){
         if (accSet.contains(objAcc.Name)){
            objAcc.addError('Account Found......');
        }
        accSet.add(objAcc.Name);   
    }   
    
    List <Account> accList = new List <Account>();
        for (Account objAcc : [select id, Name from Account where Name In : accSet]){
            accList.add(objAcc);
            
            if (accSet.equals(accList)){
                objAcc.addError('Record Alreday Found ');
            }   
    	}       

}




..
Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers


4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail
Aditya Chaturvedi 15Aditya Chaturvedi 15
@ashu 6112
Have the same doubt. If the records with same name is inserted in bulk(2 records with same name), then will this trigger avoid the duplicates. Since this code will check only the available records name in the Org. So it will work fine if the batch size is set to 1 but it fails for other scenario. 
Shubham Jain 338Shubham Jain 338
trigger AccountTrigger on Account (before insert, before update) {
    
    Set<String> accountNameSet = new Set<String>();
    for (Account acc : Trigger.new) {
        if ((Trigger.isInsert || (Trigger.isUpdate && acc.Name != Trigger.oldMap.get(acc.Id).Name))) {
            accountNameSet.add(acc.Name);
        }
    }
    if (accountNameSet.size() > 0) {
        List<Account> accountList = [SELECT Id, Name FROM Account WHERE NAME IN :accountNameSet];
        if (accountList.size() > 0 ) {
            accountNameSet = new Set<String>();
            for (Account acc : accountList) {
                accountNameSet.add(acc.Name);  
            }
            for (Account acc : Trigger.new) {
                if (accountNameSet.contains(acc.Name)) {
                    acc.addError('Account with same name already exists');
                }
            }   
        }  
    }
}
Adil Shaik (HYD)Adil Shaik (HYD)
trigger AccountTrigger on Account (before insert, before update) {
       List<Account> lst = [Select id, name from Account];
        for(Account acc:lst){
            for(Account accnew: Trigger.New){
                if(acc.Name == accnew.Name && acc.Id!= accnew.Id){
                    acc1.addError('Duplicate Account Found, Please update the Unique name to Update');
                }
            }
        }
    }
moin k 1moin k 1

The problem lies in the condition if(accountNames.size()<0). This condition will never be true because the size of a set cannot be negative.
To fix this issue, you need to change the condition to check if the size of the set is greater than 0, indicating that there are duplicate names in the Accounts
the unnecessary if condition if(setName.size() > 0 ) should remove. The preventDuplicate method will now always perform the validation logic to detect and add an error message to the Name field of any duplicate records found.
Hi Guys here is the correct code

public class AccountDuplicate {        
    public static void preventDuplicate (list<Account>Accounts){
        Set<String> accountNames = new Set<String>();
        for(Account acc: Accounts){
            accountNames.add(acc.name);
            }
        
            list<Account>lstAccount=[select id,name from Account where name in :accountNames];
            map<string,Account>mapAccount = new map<string,Account>();
            for (Account acc:lstAccount){
                mapAccount.put(acc.name,acc);
                
            }
            for(Account acc :Accounts){
                if(mapAccount.containsKey(acc.name)){
                    acc.name.addError('Dont create a dup record you fool');
                }
                
            }
        
    }

}

Trigger to call this class
trigger AccountTrigger on Account (before insert,before update,after insert,after update) {
    if(trigger.isBefore && Trigger.isInsert){
        System.debug('Calling preventDuplicate method');
      AccountDuplicate.preventDuplicate(Trigger.new); 
    }