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, I'm trying to create SOQL to list all Contact Records with the same Account Id..any idea? thanks!

Hi Guys, I'm trying to create SOQL to list all Contact Records with the same Account Id..any idea? thanks!
Hargobind_SinghHargobind_Singh
Is this something that you are trying to do, except for using AccountID instead of Name: 

https://developer.salesforce.com/forums?id=906F00000008j1lIAA
Himanshu ParasharHimanshu Parashar
HI Jayson,

You can write following soql and iterate over it.
 
List<Account> accountsWithContacts = [select id, name, (select id,description,firstname, lastname, email from Contacts) from Account];

or
 
List<Contact> contacts = [select id, salutation, firstname, lastname, email from Contact where accountId = :account.Id];

Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
 
Jayson Faderanga 14Jayson Faderanga 14
@Hargobind_Singh thanks for the suggestion..it is not actually.. I'm trying to create a trigger that works like a validation rule..it should only fire when a user attached a duplicate contact in an Account... the trigger should only query duplicates on Accounts related contacts..

@Himanshu , Thanks for the suggestion, that is exactly what I need. I just need to know how will I create the bind variable :account.id ?
Jayson Faderanga 14Jayson Faderanga 14
I got the query, I was able to List all contacts related to same Account, but how will I match my new contact email from the list of all contacts related to same account.


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

for (Contact newCon : Trigger.New) {

if (newCon.AccountId != null)

{

List <Contact> exCon = [Select Id from Contact where AccountId = :newCon.AccountId Limit 200];


if(newCon.Email ==  exCon[0].Email )

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

 }
 

}

}

it only matches the first one on the list
 
Jayson Faderanga 14Jayson Faderanga 14
guys. I get it. Thanks a lot!

this should fix it..

trigger dt 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');
  
  
  }

 }
 

}

}
Himanshu ParasharHimanshu Parashar
Yes, That is correct.

Thanks,
Himanshu