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
Jayson Faderanga 14Jayson Faderanga 14 

Hi Guys, How do I run this query outside a loop? any idea thanks


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


for (Contact newCon : Trigger.New) {

if (newCon.email != null)

 {
 
 List <Contact> exCon = [Select email from Contact where AccountId = :newCon.AccountId AND Email = :newCon.email Limit 1];
 
if (exCon.size() > 0)

  {
         newCon.addError('Duplicate Contact Found');
  
  
  }

 }
 

}
Le NguyenLe Nguyen
hi Jayson,

Here is the idea how to handle it.  I wrote with notepad, It may have errors when compiled.  However, this is just the ideas.
 
trigger duplicateContacsonAccount on Contact (before insert, before update) {
	set<id> AccountIDs = new set<id>();
	set<string> emails = new set<string>();



	for (Contact newCon : Trigger.New) {
		AccountIDs.add(newCon.AccountId);
		emails.add(newCon.email);
	 }

	 list<Contact> exCons = [Select id,email,AccountId from Contact where AccountId in :AccountIDs AND Email in :emails];

	 map<id,set<string>> map_accid_emails = new map<id,set<string>>();

	 for(Contact c: exCons){
	 	if(string.isblank(c.email))
	 		continue;
	 	set<string> sEmails = new set<string>();
	 	if(map_accid_emails.containskey(c.AccountId)){
	 		sEmails = map_accid_emails.get(c.AccountId);
	 	}

	 	sEmails.add(c.email);
	 	map_accid_emails.put(c.AccountId,sEmails)
	 }

	 for (Contact newCon : Trigger.New) {
	 	set<string> sEmails = new set<string>();
	 	if(map_accid_emails.containskey(newCon.AccountID)){
	 		sEmails = map_accid_emails.get(newCon.AccountID);

	 		if(sEmails.contains(newCon.Email)){
	 			newCon.addError('Duplicate Contact Found');
	 		}
	 	}
	 }
 }

Hope this help.

Regards,

Le