Understand the error – System.QueryException: List has no rows for assignment to SObject

Description

This issue you may encounter in apex class if you have query like this:
The following query is not returning any number of records:

Lead l = [SELECT Id FROM Lead WHERE Id = : recordId];

The error “List has no rows for assignment to SObject” occurs when query doesn’t return any rows.

Possible Reason

  • Record may does not exists.
  • Current user may not have access to view the record.
  • Record got deleted in between the transaction.
  • ‘recordId’ is malformed due code issue.

Resolution

Use List to store the query result instead direct sobject variable

List<Lead> l = [SELECT Id FROM Lead WHERE Id = : recordId];

Move code into a class marked as “without sharing”

  • Do only if issue is taking place due to access issue. Run the code in system mode so that user can access it.