+ 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.