Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

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