Newer Version Available

This content describes an older version of this product. View Latest

Using SOQL Queries That Return One Record

SOQL queries can be used to assign a single sObject value when the result list contains only one element.

When the L-value of an expression is a single sObject type, Apex automatically assigns the single sObject record in the query result list to the L-value. A runtime exception results if zero sObjects or more than one sObject is found in the list. For example:

1List<Account> accts = [SELECT Id FROM Account];
2
3// These lines of code are only valid if one row is returned from
4// the query. Notice that the second line dereferences the field from the
5// query without assigning it to an intermediary sObject variable.
6Account acct = [SELECT Id FROM Account];
7String name = [SELECT Name FROM Account].Name;

This usage is supported with the following Apex types, methods, or operators:

  • Database.query method.
  • Safe Navigation Operator. See Safe Navigation Operator.
  • Null Coalescing Operator. See Null Coalescing Operator.
  • Map.values.

    Although currently supported, Salesforce recommends against using this feature with Map.values.

    Warning