5

Simple and short question, what is the cheapest way to query (plain SOQL) if an object has child records? I want to avoid running into limits even if there are parents with millions of child records.

2 Answers 2

11

You can use a Left Inner Join to get the data you want with pure SOQL. For example:

SELECT Id FROM Parent__c WHERE Id IN (SELECT Parent__c FROM Child__c)

The joined rows do not count against your query row limit.

2

e.g.

for(Account acc:[Select Id, (Select Id From Contacts limit 1) From Account Where Id=:idVar]) {
         if(acc.Contacts != null && acc.Contacts.size() >0) {
             System.debug('Has child records.');
         } else {
             System.debug('No child records.');
         }
}
3
  • Thanks and how would this work with plain SOQL? (Without Apex) I updated the question to make that clear.
    – noBillSide
    Commented Dec 14, 2016 at 11:12
  • @TarifAbuZara [Select Id, (Select Id From Contacts limit 1) From Account Where Id=:idVar] is the query. :idVar is just there to fetch a single Account.
    – Dan Jones
    Commented Dec 14, 2016 at 11:23
  • @TarifAbuZara, if you are looking for only SOQL query without if-else then i am afraid you could do through SOQL which is possible through other RDBMS e.g. stackoverflow.com/questions/8018757/…
    – LakhanP
    Commented Dec 14, 2016 at 11:27

You must log in to answer this question.

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