Difference between SOQL and SOSL

System.QueryException: List has no rows for assignment to sObject

SOQL or Salesforce Object Query Language throws an exception when the query does not return any records that meets the conditions in the WHERE clause of the statement.

Exception Cause

The error “List has no rows for assignment to SObject” occurs when query doesn’t return any rows. This occurs when a query is written with a WHERE clause specified but it is not wrapped in a TRY CATCH statement or returned to a list, rather results are being returned to a single variable.

Example

Case c = [SELECT Id, Subject, Type FROM Case WHERE Type =: 'Support' LIMIT 1];

The assumption here is that 1 record will be returned that matches the criteria else NULL will be returned. However, if no record matches that criteria a Query Exception is thrown which fails the execution.

Exception Solution

There are multiple ways a developer can deal with this error.

1. Ensure the result is returned in a collection variable.

List<Case> cList = [SELECT Id, Subject, Type FROM Case WHERE Type =: 'Support' LIMIT 1];

OR

List<Case> cList = new List<Case>();
cList = [SELECT Id, Subject, Type FROM Case WHERE Type =: 'Support' LIMIT 1];

2. Check if the collection is empty or not

if(cList.size() > 0){
   Do Something;
}

3. Enclose the query in a Try Catch statement

Case c = new Case;

Try{
   c = [SELECT Id, Subject, Type FROM Case WHERE Type =: 'Support' LIMIT 1];
} 
Catch(System.QueryException e){
   // Perform logic here
}

Conclusion

System.QueryException is very likely to occur if the code written in Apex is not optimized and if precautions are not taken to catch those exceptions or to write correct syntax.