11

To query a single record we have below two approach :

Approach 1. Assign record to a single Account variable as shown below:

Account accountToGet = [SELECT Name From Account where name = 'UniqueAccount' LIMIT 1];

With above line, it throws below error if no record founds : System.QueryException: List has no rows for assignment to SObject

Approach 2. Assign single record to a List variable as mention below :

List<Account> lstAccount = [SELECT Name From Account where name = 'Unknown Account']; 

Even if SOQL returns no records, above line doesn't throws an error. We can use below line to avoid NULL errors.

if(!lstAccount.IsEmpty())
    System.debug('No Error');

To handle NULL exception in Approach 1, we need to handle NULL exception in try....catch. It looks like an approach where we will error to occur and then handle it in try....catch.

With Approach 2, we can avoid exception to occur and without using try..catch.. also the code will work.

Based on above approaches, I think approach 2 is fine to prevent errors. Can anyone give me suggestion that why should not we use approach 2?

  • In order to compare evenly, you might want to add the 'LIMIT 1' statement to approach 2 as well. Otherwise there might also be performance considerations which I'm assuming you are not looking for in the answer.. – Guy Clairbois May 7 '15 at 12:06
9

Approach 2 would be preferred, indeed.

The only scenario in which approach 1 could be considered is when it is absolutely necessary for the system to run that the record exists. E.g. in case of a configuration table. In that case you might always want an exception to happen.

You could also use approach 2 for that, but approach 1 is less code for that scenario.

  • Right, in other words if it is actually an error, approach 1 is appropriate. Well put. – Adrian Larson May 7 '15 at 12:05
1

I consider the second approach best practice. I try to avoid exceptions when there isn't really an error condition.

1

Option 2 is the right way. The only reason you would probably not use that is if you are worried about limit of code characters in the org or as Guy mentioned above where you really just need the code to fail when the record does not exist.

0

I think both the approaches are appropriate but it totally depends on the preference and requirement which one to use. I would recommend the second approach as SOQL always returns result as list. Here is the similar thread - What does a SOQL query return if no row is found?

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.