Sub topic 6
Handling query results safely
This chapter assumes you can write a basic inline SOQL query and know Apex collections and System.debug. It covers the three shapes a query result can take and the errors that appear when you handle them carelessly.
Three ways to receive a result
An inline query can be assigned to a list, to a single sObject, or to an Integer (for COUNT()). The list is the safest choice, because it never fails because of how many rows came back.
| Assigned to | Zero rows | One row | More than one row |
|---|---|---|---|
| `List<Account>` | Empty list | List of one | List of all rows |
| `Account` | `QueryException` | The record | `QueryException` |
| `Integer` with `COUNT()` | `0` | Row count | Row count |
Guard against empty results
Assigning a query to a single record is a common source of runtime errors. If no row matches, Apex throws a QueryException with the message "List has no rows for assignment to SObject". If more than one row matches, it throws the same exception type. Query into a list and check it first.
List<Account> accts = [
SELECT Id, Name FROM Account WHERE Name = 'No Such Account' LIMIT 1
];
if (!accts.isEmpty()) {
System.debug(accts[0].Id);
}
// Assigning directly to a single record throws a QueryException when no row matches:
// Account a = [SELECT Id FROM Account WHERE Name = 'No Such Account' LIMIT 1];
Integer total = [SELECT COUNT() FROM Account];The LIMIT 1 makes the list hold at most one record. Use isEmpty() instead of checking accts.size() > 0, because it states the intent directly.
Only read fields you queried
A query returns only the fields in its SELECT clause, plus Id. Reading any other field throws an SObjectException: "SObject row was retrieved via SOQL without querying the requested field".
Account a = [SELECT Id FROM Account LIMIT 1];
// a.Name is not in the SELECT list, so this line would throw an SObjectException:
// System.debug(a.Name);Writing to such a field is allowed, so the error only appears when you read it. Add the field to the query to fix it.
Handle null field values
A field that holds no value comes back as null. Calling a method on it, such as a.Industry.toLowerCase(), throws a NullPointerException. Compare against null first.
List<Account> accts = [SELECT Id, Industry FROM Account LIMIT 5];
for (Account a : accts) {
String industry = (a.Industry != null) ? a.Industry : 'Unknown';
System.debug(a.Id + ': ' + industry);
}Choosing a result shape
Common errors
QueryExceptionon assignment: a single-record assignment found zero or several rows. Use a list.ListException: you indexed an empty list. CheckisEmpty().SObjectException: you read a field that the query did not select. Add it toSELECT.NullPointerException: you called a method on a null field value. Check fornull.
Exercise
A query ends with LIMIT 1 and is assigned directly to an Account variable. When does it throw a QueryException, and how do you rewrite it so it never does?
Show answer
It throws when no account matches, because there is no row to assign. Query into a List<Account>, check !accts.isEmpty(), and then read accts[0].
Exercise
This code throws an error. Which exception is it, and what is the fix? Contact c = [SELECT Id FROM Contact LIMIT 1]; System.debug(c.Email);
Show answer
It throws an SObjectException, because Email was not in the SELECT list. Change the query to SELECT Id, Email FROM Contact LIMIT 1. The assignment to a single record also fails with a QueryException if the org has no contacts, so a list with an isEmpty() check is safer.