Sub topic 6
Handling query results safely
A SOQL query in Apex can return a list, a single record, an Integer, or a list of AggregateResult rows. Each shape fails in its own way. This chapter covers the failures that production code hits most often, and how to avoid them.
This chapter assumes you can write an inline query with SELECT, FROM and WHERE, and that you know Apex lists, maps and try/catch. You can run the examples as anonymous Apex in the Developer Console or an IDE.
What a query returns
The type on the left of the assignment decides what Apex expects from the query.
| Assigned to | Query form | Behavior |
|---|---|---|
| `List<Account>` | `SELECT Id, Name FROM Account` | Always a list, possibly empty. Never `null`. |
| `Account` | `SELECT Id FROM Account LIMIT 1` | Exactly one row, or a `QueryException`. |
| `Integer` | `SELECT COUNT() FROM Account` | The row count. |
| `List<AggregateResult>` | `SELECT COUNT(Id) c FROM Account` | One row per group, read with `get()`. |
The list form is the safest default. A list absorbs zero, one or many rows without throwing.
The single-record trap
Assigning a query straight to one sObject works only when exactly one row comes back. Zero rows and more than one row both throw a QueryException.
// Zero rows: "List has no rows for assignment to SObject"
try {
Account a = [SELECT Id FROM Account WHERE Name = 'No Such Account'];
} catch (QueryException e) {
System.debug('No match: ' + e.getMessage());
}Adding LIMIT 1 fixes the "more than one row" case. It does not fix the "no rows" case. The safe pattern queries into a list and checks it first:
List<Account> matches = [
SELECT Id, Name FROM Account WHERE Name = 'No Such Account' LIMIT 1
];
if (matches.isEmpty()) {
System.debug('Nothing found');
} else {
Account found = matches[0];
System.debug(found.Id);
}Use isEmpty() rather than matches.size() == 0. It reads better and states the intent directly.
When a single-record assignment is acceptable
Direct assignment is fine in a test, where you created the one record yourself and a failure should stop the test. It is also reasonable in code where a missing record means a real bug and you want a loud failure. In every other case, use a list.
Counting without loading rows
If you only need a number, do not query rows and call size(). Rows count against heap memory and the query row limit. SELECT COUNT() returns an Integer directly.
Integer total = [SELECT COUNT() FROM Account WHERE Industry = 'Technology'];
System.debug('Technology accounts: ' + total);SELECT COUNT() with no field is the form that returns an Integer. SELECT COUNT(Id) returns an AggregateResult list instead. Assigning it to an Integer fails to compile.
Reading only the fields you queried
An sObject returned from a query holds only the fields in the SELECT clause, plus Id. Reading any other field throws an SObjectException. The compiler cannot catch this, so it shows up at runtime.
Account seed = new Account(Name = 'Field Demo', Industry = 'Technology');
insert seed;
Account a = [SELECT Id FROM Account WHERE Id = :seed.Id];
try {
System.debug(a.Name);
} catch (SObjectException e) {
// "SObject row was retrieved via SOQL without querying the requested field"
System.debug(e.getMessage());
}The fix is to add the field to the query. Two habits prevent this error:
- Put every field a method reads into its
SELECTclause, and keep the query next to the code that uses it. - When a helper method receives an sObject from a caller, document which fields it needs, or re-query inside the helper by
Id.
A field that was queried but holds no value is different. It is null, and reading it is safe.
Guarding relationship fields
A child-to-parent query returns the parent through dot notation. When the lookup is empty, the parent is null, and reading a field on null throws a NullPointerException.
List<Contact> contacts = [
SELECT Id, LastName, Account.Name
FROM Contact
LIMIT 20
];
for (Contact c : contacts) {
// c.Account.Name would throw for a Contact with no Account
String accountName = c.Account?.Name;
System.debug(c.LastName + ' works at ' + (accountName ?? 'no account'));
}The safe navigation operator ?. returns null when the left side is null instead of throwing. The null coalescing operator ?? supplies a fallback. Together they replace a nested if check.
Remember that Account.Name is available only because the query selected it. The same rule about unqueried fields applies to parent fields.
Aggregate results and casting
An aggregate query returns AggregateResult rows. Each value comes back as Object, so you cast it. Use the alias you gave in the query as the key. Fields without an alias get generic names like expr0, which are fragile.
List<AggregateResult> results = [
SELECT Industry, COUNT(Id) total, SUM(AnnualRevenue) revenue
FROM Account
WHERE Industry != null
GROUP BY Industry
];
for (AggregateResult ar : results) {
String industry = (String) ar.get('Industry');
Integer total = (Integer) ar.get('total');
Decimal revenue = (Decimal) ar.get('revenue');
System.debug(industry + ': ' + total + ', ' + revenue);
}Two cautions apply:
SUMover rows where the field is empty can returnnull. Assigning that to aDecimalis fine. Doing arithmetic on it is not, so check fornullfirst.- A query with an aggregate function and no
GROUP BYalways returns exactly one row, even when no records match.COUNT(Id)gives0in that case, butSUMgivesnull.
Turning results into a map
A map keyed by Id is the standard way to look up records without a nested loop. The Map constructor accepts a query directly.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Industry = 'Technology']
);
Id someId = accountsById.isEmpty() ? null : new List<Id>(accountsById.keySet())[0];
Account hit = accountsById.get(someId);
if (hit != null) {
System.debug(hit.Name);
}Map.get() returns null for a missing key and does not throw. Always check the returned value before reading its fields. This pays off in bulk code, where a lookup can miss for a record whose parent was deleted or filtered out.
The constructor only accepts a list of sObjects of one type. A map built this way also gives you keySet() and values(), which are useful for passing the same Ids to a later query.
Treating results as copies
A query result is a snapshot. Changing a field on a returned record changes only the in-memory copy until you run DML.
List<Account> accts = [SELECT Id, Name FROM Account LIMIT 1];
if (!accts.isEmpty()) {
accts[0].Name = 'Renamed in memory';
// The database still holds the old name until you call update.
update accts;
}Re-running the query after a change returns fresh data. Re-running it without calling update returns the original value.
A defensive checklist
- Query into a
Listunless a missing row should fail loudly. - Check
isEmpty()before reading[0]. - Select every field you will read, including parent fields.
- Use
?.and??for relationship fields that may be empty. - Give aggregate expressions aliases, and cast each value to its real type.
- Check
Map.get()results fornull.
Exercise
A method runs Contact c = [SELECT Id, Email FROM Contact WHERE LastName = :name LIMIT 1];. It works in testing but throws a QueryException in production for some names. Why, and how do you fix it?
Show answer
LIMIT 1 prevents the "more than one row" error, but a name with no matching Contact returns zero rows, and assigning zero rows to a single sObject throws a QueryException. Query into a List<Contact>, check isEmpty(), and read [0] only when the list has a record.
Exercise
A query selects SELECT Id, Name FROM Contact. A later line reads c.Account.Name, and a different line reads c.Email. Which lines fail, and why?
Show answer
Both fail. Email was not selected, so reading it throws an SObjectException. Account.Name was not selected either, so the parent relationship is not loaded and the read also throws an SObjectException. Add Email and Account.Name to the SELECT clause. After that, use c.Account?.Name because a Contact may have no Account.