When you assign a SOQL query directly to a single sObject variable, Salesforce expects exactly one record to be returned. If the query returns no
records, the system throws a QueryException with the message "List has no rows for assignment to SObject".
This exception occurs because SOQL queries always return a List internally, even when you assign the result to a single sObject variable. When the
List is empty, Salesforce cannot extract a single record to assign to your variable.
This pattern is particularly risky when:
- Your query includes WHERE clauses that might not match any records
- You use LIMIT clauses that could result in zero records
- You query based on user input or dynamic conditions
The exception will cause your code to fail at runtime, potentially breaking user workflows or automated processes.
What is the potential impact?
Runtime failures can occur when queries return no results, causing QueryException to be thrown. This can break user workflows,
interrupt automated processes, and create poor user experiences. In batch processing or trigger contexts, these exceptions can cause entire
transactions to fail.