System.QueryException: List has no rows for assignment to SObject: meaning and how to fix it
Quick answer
System.QueryException: List has no rows for assignment to SObject: Apex assigned the result of a query straight to a single record, but the query returned no rows (or more than one, which gives a different message). Start with: Assign the query to a List and check isEmpty() or size() before using it.
Typical message: System.QueryException: List has no rows for assignment to SObject
Cause
Apex assigned the result of a query straight to a single record, but the query returned no rows (or more than one, which gives a different message).
How to fix System.QueryException: List has no rows for assignment to SObject
- Assign the query to a List and check isEmpty() or size() before using it.
- Or add LIMIT 1 and handle the empty case.
- In tests, create the data the query expects.
List<Account> rows = [SELECT Id FROM Account WHERE Name = :n LIMIT 1];
if (!rows.isEmpty()) {
Account a = rows[0];
} Have a different message? Paste it into the error decoder, which matches it against 45 common Salesforce errors in your browser.
Frequently asked questions
What does System.QueryException: List has no rows for assignment to SObject mean in Salesforce?
Apex assigned the result of a query straight to a single record, but the query returned no rows (or more than one, which gives a different message).
How do I fix System.QueryException: List has no rows for assignment to SObject?
1. Assign the query to a List and check isEmpty() or size() before using it. 2. Or add LIMIT 1 and handle the empty case. 3. In tests, create the data the query expects.
More SOQL and queries errors
SFDX Talk is unofficial documentation. It is not affiliated with, endorsed by, or sponsored by Salesforce, Inc. Message text varies slightly by release and context, so confirm against the official page before relying on it.