While using the following null check statement :

if (Loan.Existing_Loan_Details__r != null) 

I get below error:

System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop

In this case,Loan is parent object and Existing_Loan__Details__r(28 records) is child object.I have used the sub queries to access Existing_Loan__Details__r child object along with other child objects of Loan sobject. The number of records are less than 200 even after considering all the child objects of Loan.Still getting the same error. How should I check null condition to avoid null pointer exception?

  • Are you sure that is the line that’s throwing the error
    – Eric
    Commented Jan 21, 2018 at 8:26
  • Hi Eric, Yes I'm sure about it.Had added debug statements before and after it. Commented Jan 22, 2018 at 9:58

1 Answer 1


The if statement is not necessary at all; a relationship that has been queried is guaranteed to be a not-null value (specifically, it will be a list of the appropriate SObject type).

If you need just one item (e.g. to test the presence of any child), add LIMIT 1 to the sub-query. If you need all the items, you should generally use the for-each loop syntax:

for(Loan_Detail__c detail: Loan.Existing_Loan_Details__r) {

If there are no items, this loop will do nothing. If there are items, then the loop's body will execute once for each Loan_Detail__c.

  • Yes @sfdcfox, I also thought same,had made the changes to take the Loan.Existing_Loan_Details__r records into list using a for loop and then applied null check on list to proceed.Will verify and share the same if it works,have send it for deployment.Thanks:) Commented Jan 22, 2018 at 10:01
  • 1
    Just tried this, but now am running into a Invalid Query Locator error. I think I'm trying to pull too many related records in one shot Commented Feb 21, 2019 at 19:56

You must log in to answer this question.

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