Best Approach/Way to Query Single SObject record

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?

Answer

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.

Attribution
Source : Link , Question Author : Ashish , Answer Author : Guy Clairbois

Leave a Comment