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
andrew_mowatandrew_mowat 

Avoid List Has No Rows Errors

Hi All,

 

I am wondering if there is a clever way to avoid getting an error message when a query returns no results.  At the moment it throws a 'List has no rows for assignment to SObject' error.

 

An example of a query would be :

 

Fund_Asset_Class_Link__c draftFundAwaitingApproval = [ select Fund__r.Id from Fund_Asset_Class_Link__c where Fund_Asset_Class__r.Id =: fac.Parent__r.Id and Fund__r.Fund_Status__c='Awaiting Approval' ];

 

If there are no Fund_Asset_Class_Link__c's meeting the query criteria I get an error.

 

One way I've seen to possibly avoid this is to do something like:

 

if ( [ select Fund__r.Id from Fund_Asset_Class_Link__c where Fund_Asset_Class__r.Id =: fac.Parent__r.Id and Fund__r.Fund_Status__c='Awaiting Approval' ].size() >0 ) {

 

Fund_Asset_Class_Link__c draftFundAwaitingApproval = [ select Fund__r.Id from Fund_Asset_Class_Link__c where Fund_Asset_Class__r.Id =: fac.Parent__r.Id and Fund__r.Fund_Status__c='Awaiting Approval' ];

 

}

 

But this clearly creates two queries, and I'll quickly hit restriction limits this way.

 

Any thoughts on how to get around this?

 

Many thanks,

Andrew

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Anand@SAASAnand@SAAS

Yes it is a two step process but you can store the result of the SOQL in a list and look at the list.size() to proceed further. For e.g.:

 

 

List<Fund_Asset_Class_Link__c> results =  [ select Fund__r.Id from Fund_Asset_Class_Link__c where Fund_Asset_Class__r.Id =: fac.Parent__r.Id and Fund__r.Fund_Status__c='Awaiting Approval' ];
if (!results.IsEmpty() >0 ) {
 
Fund_Asset_Class_Link__c draftFundAwaitingApproval =results[0];
 
}

 

 

All Answers

Anand@SAASAnand@SAAS

Yes it is a two step process but you can store the result of the SOQL in a list and look at the list.size() to proceed further. For e.g.:

 

 

List<Fund_Asset_Class_Link__c> results =  [ select Fund__r.Id from Fund_Asset_Class_Link__c where Fund_Asset_Class__r.Id =: fac.Parent__r.Id and Fund__r.Fund_Status__c='Awaiting Approval' ];
if (!results.IsEmpty() >0 ) {
 
Fund_Asset_Class_Link__c draftFundAwaitingApproval =results[0];
 
}

 

 

This was selected as the best answer
andrew_mowatandrew_mowat

Great, thank you, worked a treat!