+ Start a Discussion

i need a trigger to restrict duplicate record based on more 2 fields (before insert, before update)

pranab khatuapranab khatua

You can generate Unique string variable using more 2 fields and store them into set.

Query from Object with more 2 fields and store in MAP object with key will be 2 more fields Unique string.

In New Trigger list you have to check that map with generated Unique variable. Then you need to use AddError method prevent duplicate record.

Please choose best answer if you help it.

Suraj TripathiSuraj Tripathi
Hi vijayabhaskarareddy ,'

You can try this -
trigger AccountDuplicateTrigger on Account (before insert,before update) {

     //You may need to filter this a bit more if you have a very large number of accounts    
     map<Id,Account> existingAccountMap = new  map<Id,Account>([Select Id, Name, Rating From Account Where Rating != null]); 

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

Kindly mark this as solved if it's resolved so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

hi@ Suraj

I m getting below error 

Review all error messages below to correct your data.
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 7, column 1
Shailesh RawteShailesh Rawte
Hi vijayabhaskarareddy ,

trigger AccountTrigger on Account (before insert,before update) {
for(Account a : Trigger.new)
   // Here you have to fetch the data base on your new record if you got the data add error message
// either you  fetch all data outside the for loop and store it into map  and then you can check inside the for loop
 // like select field1,field2 where field1.a.field1


Thanks & Regards
Shailesh Rawte
v varaprasadv varaprasad
Hi Vijay,

Please check once below code : 
trigger AccountDuplicateTrigger on Account (before insert,before update) {

     list<account> lstofExistingAccs = [select id,name,rating from account where rating != null];       
     map<string,string> mapOfAccountfields = new  map<string,string>();
     for(Account a : lstofExistingAccs){
         if(a.name != null && a.Rating != null){
             mapOfAccountfields.put(a.name, a.Rating);
    for(account acc : trigger.new){
        if(mapOfAccountfields.containsKey(acc.name) &&  acc.rating == mapOfAccountfields.get(acc.name)){
            acc.addError('Account name and rating already exists');

Hope it helps you.
Please let me know in case of any other assistance.