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
kathyanikathyani 

No rows assigned to SObject

Case 1 --- ABC__c  a = [select a.Id, a.name from A where a.label = 'apex'];

Case 2 --- List <ABC__c> a = [select a.Id, a.name from A where a.label = 'apex'];


In case of Case 1 , if there is no matching record then it throws an exception when run (no row assigned to Sobject) whereas Case 2 does not throw an exception.

For now I am using syntax of Case 2 in my coding but how can I make the code (Case 1) more efficient without having to use a list as defined in Case 2.

I need to use this in many places, any help would be appreciated.



thanks,
kathyani



aalbertaalbert
Unless you can guarantee that the SOQL query will return one and only one record, then you will want to use the solution in Case 2, returning into a List.
Apex , as you noticed, will throw an exception if 0 or more than 1 record is returned and your return type is a single object (and not a List).

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/langCon_apex_SOQL_single_row.htm

iceberg4uiceberg4u
y not use 'limit 1' in your query.
boihueboihue
Hi,
The Case 1 should be changed like these:
     ABC__c[ ]  a = [select a.Id, a.name from ABC__c a where a.label = 'apex'];
or
     ABC__c  a = [select a.Id, a.name from ABC__c a where a.label = 'apex' Limit 1];
 
In the first command, you can verify if there's any retrieved records by using:
     if (a.Size() !=0)
 
Regards,
Boi Hue