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
JarrettKJarrettK 

What is the best way to query an object if you are not sure there will be results

I would like to know the best practices for querying data on an object if you do not know if any rows will be returned.

 

For example:

 

List<CustomObject__c> myObj = [select Id from CustomObject__c where customField__c = '1234' limit 10];

 

This may not return any results and will error out.

 

However assigning the data to an array does not care if there are zero results

 

CustomObject__c[] myArray = [select Id from CustomObject__c where customField__c = '1234' limit 10]; 

 

But I really want my data reutned in object format for DML and other benefits, what is the best way of converting an array to object notation?  

 

I am sure I am missing something really stupid, please advise.

 

Thanks!

 

Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

List<CustomObject__c> myObj = [select Id from CustomObject__c where customField__c = '1234' limit 10];

 

This will also do not give you any error you can use it. If no record return then list will be empty, you can check myObj.isEmpty or myObj.size() > 0 before using it.

 

The error that you are concerned about : List has no rows for assignment to SObject

will come only when you assign it to sObject directly and no result are returned.

 

CustomObject__c  myObj =  [select Id from CustomObject__c where customField__c = '1234' limit  1];

 

So go ahead with this

 

List<CustomObject__c> myObj = [select Id from CustomObject__c where customField__c = '1234' limit 10];

 

No issues in this .

All Answers

Shashikant SharmaShashikant Sharma

List<CustomObject__c> myObj = [select Id from CustomObject__c where customField__c = '1234' limit 10];

 

This will also do not give you any error you can use it. If no record return then list will be empty, you can check myObj.isEmpty or myObj.size() > 0 before using it.

 

The error that you are concerned about : List has no rows for assignment to SObject

will come only when you assign it to sObject directly and no result are returned.

 

CustomObject__c  myObj =  [select Id from CustomObject__c where customField__c = '1234' limit  1];

 

So go ahead with this

 

List<CustomObject__c> myObj = [select Id from CustomObject__c where customField__c = '1234' limit 10];

 

No issues in this .

This was selected as the best answer
JarrettKJarrettK

Thank you for clerifying, it understand now.