I want to filter out the contacts only if they have at least 1 serviceContract associated to it ?

I know this is possible using apex ( query all childs in inner query and iterate through using .size() operator.) But is there any alternate to put this condition in SOQL itselsf ?

Ex: Contact is a Parent and ServiceContracts are child to it.

Say, Can I have any alternate to this query ?

Select ID, (Select ID from ServiceContracts where size() >0) from contact limit 10

1 Answer 1


You can do something like that:

SELECT Id FROM Contact WHERE Id IN (SELECT ContactId FROM ServiceContract) LIMIT 10

Limits.getQueries() will return only 1 SOQL.

  • 1
    It would be good to provide a link to the documentation and make reference to the term "semi-join" to help understand what this is doing.
    – Phil W
    Commented Nov 17, 2022 at 16:07
  • 2
    Also useful.
    – Adrian Larson
    Commented Nov 17, 2022 at 16:16
  • 2
    N.B. Parent-Child subqueries and semi/anti joins don't count towards the 100 SOQL query limit, but they do count towards the lesser-known 300 "aggregate query" limit. Limits.getAggregateQueries() would return "1" here (as opposed to returning "0" if the semi-join in this answer were removed).
    – Derek F
    Commented Nov 17, 2022 at 17:18

You must log in to answer this question.

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