Search code examples
salesforcesoqlforce.com

SOQL Get Name from nested SELECT statement


I have an SOQL query that is grabbing information from an Opportunity in Salesforce and then grabbing the ContactID of a related contact role. It is only displaying opportunities that have a different child object of a certain type. I would like to extract and display the name of the contact role in my table. Suggestions?

SELECT ID, Name,

(SELECT contactID
FROM opportunitycontactroles
WHERE IsPrimary = TRUE)

FROM Opportunity

WHERE ID IN

(SELECT opportunity_ID FROM 
opportunity_child WHERE 
opportunity_child_picklist = 'Specific Item')

I would like to get the 'Name' field from the contactID found from the Opp. Contact Roles table and display it with the Opportunity ID as well.


Solution

  • You can follow the contact relationship in the subquery, e.g.

    SELECT ID, Name,
    
    (SELECT contactId, contact.name
    FROM opportunitycontactroles
    WHERE IsPrimary = TRUE)
    
    FROM Opportunity
    
    WHERE ID IN
    
    (SELECT opportunity_ID FROM 
    opportunity_child WHERE 
    opportunity_child_picklist = 'Specific Item')