I'm trying to create an apex class and visualforce page to create a query that pulls all contacts that the Picklistfield__c contains "associate". we also want to add a sub query that will pull another contact record's name where the lookupfield__c is referenced to the Id of the current contact in the query. the idea is below:

SELECT Name, Email, Phone, 
    (SELECT Name FROM Contacts Where lookupfield__c = *currentContactId* )
FROM Contact
WHERE Picklistfield__c LIKE '%Associate%'


Is it possible to pull the ID of the current contact record in the query and use it in as filter for the sub-query.

I do apologize for in advance if I named them incorrectly as I'm not a certified developer. 

1 Answer 1


That is pretty simple to achieve. In Salesforce Setup if you open the Custom LookupField "lookupfield__c" in Object Manager you will see the "Child Relationship Name". That's the name you provided when creating the lookup. Given this child relationship name is "CustomContacts" you can simply query:

SELECT Name, Email, Phone, (SELECT Name FROM CustomContacts__r) FROM Contact WHERE Picklistfield__c LIKE '%Associate%'

Note: When you iterate over the Contacts in APEX you need to have a nested for Loop.

for(Contact con : associateContacts){
    //do something with main contact;

    for(Contact child : con.CustomContacts){
        //process child records;
  • 1
    This is close to correct. For custom relationships, you'll need to add __r to the end of the child relationship name in the subquery. I like to think of it as the __c stands for "custom" and the __r stands for "relationship".
    – Derek F
    Oct 23, 2023 at 11:12
  • Also, while I think it's a good idea/safe to always use a nested loop to access child records, it's not always required. If you have less than ~200 child records per parent, then you can access the embedded List<SObject> directly.
    – Derek F
    Oct 23, 2023 at 11:14
  • Thanks @Derek F. I was able to create the query with your guidance. I'm a solo admin so this type of approach will help me in the future. Cheers! Oct 24, 2023 at 10:20

You must log in to answer this question.

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