Newer Version Available
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;