You need to sign in to do that
Don't have an account?

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!
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
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 .
Thank you for clerifying, it understand now.