I have the following many-to-many relationship, linking "Contact" and "Distribution_List__c" with the "Distribution_List_Junction__c" object:

Contact - Distribution_List_Junction__c - Distribution_List__c

Given a particular Distribution List name, I am trying to retrieve the email addresses of its member Contacts. So far I have the following, which seems to retrieve Contact IDs as child records:

SELECT (select Contact__c from Distribution_List_Junctions__r ) FROM Distribution_List__c WHERE Name = 'Distribution List 1'

However, I'm not sure where to go from here. I assume that I will have to then query the Contacts object based on those Contact IDs, but I can't tell how to do that efficiently. Is it even necessary to do the separate query?

I'd really appreciate your help.

2 Answers 2


as stated above that's how you would form the query, then to access the data you would do something like this:

for (Distribution_List__c dl : [SELECT (SELECT Contact__c, Contact__r.Email FROM Distribution_List_Junctions__r ) FROM Distribution_List__c WHERE Name = 'Distribution List 1') {
  if (dl.Distribution_List_Junctions__r != null && !dl.Distribution_List_Junctions__r.isEmpty()) {
    // access it by for loop or by dl.Distribution_List_Junctions__r[0].Contact__r.Email
    for (Distribution_List_Junctions__c dlj : dl.Distribution_List_Junctions__r) {
      //do something with dlj.Contact__r.Email

I know I had issues at first figuring out how to access the data, and there are still a few more ways you can do it, it just depends on what you need to do with it :-)

  • Junctions will always be != null so that 1 check can be skipped. They might be an empty list but still - something will be there. And we don't have "above" here, nobody says your answer won't be upvoted over mine eventually, it is more helpful after all ;)
    – eyescream
    Jan 23, 2014 at 19:22
  • :-) i tend to over check for null sometimes :-P Jan 23, 2014 at 20:05
  • Thank you SalesForceGirl! This was the part I was missing. You're a star.
    – Rob
    Jan 24, 2014 at 9:39
  • no problem :-) its the part i was first stuck on lol, let me know if you need anything else, or how you are trying to use the data Jan 24, 2014 at 16:50

Go "up" on Contact:

    (select Contact__c, Contact__r.Email from Distribution_List_Junctions__r ) 
FROM Distribution_List__c 
WHERE Name = 'Distribution List 1'
  • Thank you eyescream - together your and SalesForceGirl's answers solved my problem!
    – Rob
    Jan 24, 2014 at 9:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .