+ Start a Discussion

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.


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).


y not use 'limit 1' in your query.
The Case 1 should be changed like these:
     ABC__c[ ]  a = [select a.Id, a.name from ABC__c a where a.label = 'apex'];
     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)
Boi Hue