You need to sign in to do that
Don't have an account?

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 ');
}
}
}
}
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 ');
}
}
}
}
Please try below code.
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
Hi Sonam,
Please try below code:
If you found error in above code, try below one:Let me know if you face any issues.
Thanks,
Gaurav
Email: gauravgarg.nmim@gmail.com
Please try below code.
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
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');
}
}
}
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);
why u did use list n set if we can do through map....could u plz explain me.
Below post can be used to avoid Duplicate Fields by using trigger :
@ arti rathod I have used Map in the below code
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.
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
@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
Code to check for Duplicate Account using Map.
@GauravGarg pls learn some programminng and post here. You are searching name in the id field.
Can someone post a fresh bulkified code for Duplicate Account list.
Thanks in advance
follow this link Trigger to prevent creating duplicate accounts in salesforce (https://lovesalesforceyes.blogspot.com/2020/05/triggger-to-prevent-duplicate-accounts.html)
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');
}
}
}
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');
}
}
}
{
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);
}
}
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
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.
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');
}
}
}
}
}
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');
}
}
}
}
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);
}