Loading

Apex error 'List has no rows for assignment to SObject'

Дата публикации: Jun 22, 2026
Описание

In Salesforce Apex, a SOQL query can be assigned directly to a single SObject variable using shorthand syntax. This assumes the query returns exactly one row. If the query returns zero rows, Apex throws the exception:
"List has no rows for assignment to SObject"

This error occurs when a WHERE clause in the SOQL query matches no records, and is particularly common in:

  • Apex triggers querying custom objects with user-specific filter conditions
  • Developer code using direct SObject assignment without null checks

The following query, for example, generates this error if no Account has the specified ID: [SELECT Id FROM Account WHERE Id = :Trigger.new[0].Account__c]

Решение

Root Cause

The shorthand SObject assignment syntax in Apex assumes exactly one row is returned. It does not return null when zero rows are found — instead, it throws a System.QueryException. This behavior is different from what many developers expect, especially those coming from Java where a null result would be returned.
The following unsafe pattern will throw the exception if no Player__c record matches the username value. The player != null check is never reached because the exception is thrown before the assignment completes.
(See unsafe code example)
Player__c player = [SELECT Id from Player__c where Name = :username];
if (player != null)
 p = player.Id;

Recommended Fix

Use a List-based query instead of a direct SObject assignment. This approach safely handles zero-row results:
  1. Query into a List<SObjectType> variable
  2. Check list.size() > 0 before accessing the first element
  3. Only assign the record if the list is non-empty
This pattern ensures that if the WHERE clause returns no records, the list is simply empty and the code continues safely without throwing an exception.
(See safe code example)
Player__c[] players = [SELECT Id from Player__c where Name = :username];
if (players.size() > 0)
p = players[0].Id;
Use this pattern as a best practice whenever querying custom objects or any query that includes a WHERE clause that might return zero records.
Номер статьи базы знаний

000385697

 
Загрузка
Salesforce Help | Article