3

I'm doing a query to an object. My question is if nothing returns is it technically null. I want to return null if it is.

People person = [SELECT Id, Type FROM People WHERE (Type LIKE '%Construction%') limit 1];

if (person == null){
    return null;
}
6

The syntax in your code throws a QueryException if you try it, and there are no records to return. Instead, use one of the other common patterns. This is one that I use:

People person; // is null
for(People record: [SELECT Type FROM People WHERE Type LIKE '%Construction%' LIMIT 1]) {
  person = record;
}
return person; // will return null or a single record
  • The syntax in your code throws a QueryException if you try it -- only if there's no record returned. – Jayant Das Mar 20 at 21:53
  • @JayantDas That's what I meant, of course, but I went ahead and clarified. – sfdcfox Mar 21 at 0:50
3

One way to do this is to check for the number of records returned:

People[] persons = [...];
if (persons.size() == 0) return null;

as your code as written will generate this exception if no records match:

System.QueryException: List has no rows for assignment to SObject

  • 2
    Or simply isEmpty() :) – Eric Mar 21 at 4:10
  • @Eric I always forget that method... – Keith C Mar 21 at 8:04
1

Change the code to:

People[] people = [SELECT Id, Type FROM People WHERE (Type LIKE '%Construction%') LIMIT 1];

if (people.size() == 0){
    return null;
} else {
    return people[0];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.