3

I would like to retrieve the list of Opportunities which have at least one OpportunityContactRole with role equal to test

Right now, I am doing the below query but it retrieves all the rows in the opportunity table..

[SELECT Id,
    (SELECT Id FROM OpportunityContactRoles WHERE Role = 'test')
FROM Opportunity 
WHERE IsClosed = TRUE AND IsWon = TRUE];

Is there any better alternative for this??

1 Answer 1

2

You have two options. Which approach to use depends on what else you're trying to do.

1. Query from the child object:

[SELECT Id, OpportunityId
 FROM OpportunityContactRoles
 WHERE Opportunity.IsClosed = TRUE
    AND Opportunity.IsWon = TRUE
    AND Role = 'test']

You can then loop over these results to get unique Opportunity Ids.

2. Use a second sub-query in your WHERE clause:

[SELECT Id,
    (SELECT Id FROM OpportunityContactRoles WHERE Role = 'test')
FROM Opportunity 
WHERE IsClosed = TRUE AND IsWon = TRUE
    AND Id IN (SELECT OpportunityId FROM OpportunityContactRoles WHERE Role = 'test')];

This approach filters the main query based on the records found in the sub-query.

1
  • As I need this query on the Opportunity Trigger 2nd Option is easy for me..Thanks
    – javanoob
    Commented Jul 13, 2015 at 18:34

You must log in to answer this question.

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