function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kevin BromerKevin Bromer 

Safely check for child objects from soql

Hey all-

 

Have some soql like this:

Opportunity o = [select id (SELECT id from Opportunity.ChildObject__r) from Opportunity limit 1];

 I want to reference the id on the first child object, so I do:

id myid = o.ChildObject__r[0].id;

 However, if there is no ChildObject for Opportunity o, that throws a null reference exception. I tried checking it like this:

if (o.ChildObject__r[0] != null)

 

But that also produces a null reference exception.

I know o exists, and I know there are no ChildObjects for o (for this example).  I'm sure I'm mising something obvious - any thoughts?

Thanks-

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Starz26Starz26

I believe the SOQL should be

 

Opportunity o = [select id (SELECT id from ChildObject__r) from Opportunity limit 1];

 

I believe your original query returned no results so o was null and thus you could not dereference it to o.ChildObject__r[0]

 

you could also do a test for

 

if(o.ChildObject__r.size()>0)

All Answers

Starz26Starz26

I believe the SOQL should be

 

Opportunity o = [select id (SELECT id from ChildObject__r) from Opportunity limit 1];

 

I believe your original query returned no results so o was null and thus you could not dereference it to o.ChildObject__r[0]

 

you could also do a test for

 

if(o.ChildObject__r.size()>0)

This was selected as the best answer
Kevin BromerKevin Bromer

Ah, didn't realize you could call the size method on the inner list like that. That did the trick - thanks!