Activity › Forums › Salesforce® Discussions › System.Query Exception
-
System.Query Exception
Posted by chanchal kumar on August 30, 2018 at 11:47 AMWhat is this error “System.Query Exception: List has no rows for assignment to s-object”?
shariq replied 7 years, 9 months ago 3 Members · 2 Replies -
2 Replies
- [adinserter block='9']
-
Hi,
Any error related to query will give this exception.
for example:-
- String not correctly setup in dynamic query – ‘select id from contact where id = ‘testId”
How to handle it-
When attempting to fetch a single record from the database it is easy to run into the above exception. I’ve seen two schools of thought in dealing with this issue – mostly in the forums – and have been hoping to find a more official standpoint.
I’ll describe the patterns and perhaps you can help me decide.
The Try-Catch Pattern
Surround your query by a try-catch block.
Fetch the record into a single object type variable.
Either the query successfully executes, or the exception is caught and you deal with it appropriately.
An example,MyObject__c obj;
try{
obj = [SELECT id FROM MyObject__c WHERE name=:previouslyDefinedVar];
} catch(System.QueryException e){
// Perform logic here
}
The Only Use Lists For Query Results PatternFetch records into Lists of objects. Do this even if you only expect a single row to be returned. [Queries that return values into Lists do not throw the above exception]
Check the size of the list(perhaps with an if-statement) and only perform required actions on the record if the list has a size of 1.
List<MyObject__c> objects = [SELECT id FROM MyObject__c WHERE name=:previouslyDefinedVar];if(objects.size()==1){
// Perform Logic
}
Hope this helps.
Log In to reply.