Sub topic 2
Running SOQL Inline in Apex
This chapter assumes you can write basic Apex (variables, collections, loops, classes), know the Salesforce data model, and can run anonymous Apex in the Developer Console or an IDE. You will learn how to put a SOQL query directly in Apex code and what type the query returns.
What an inline query is
An inline query is a SOQL statement written in square brackets inside Apex. The compiler checks the object and field names when you save the class, so a typo in Industri fails at compile time instead of at runtime.
The query returns a value you can assign to a variable. The type of that variable decides how the result is shaped.
List<Account> accts = [
SELECT Id, Name, Industry
FROM Account
WHERE Industry = 'Technology'
ORDER BY Name
LIMIT 10
];
for (Account a : accts) {
System.debug(a.Name + ' - ' + a.Industry);
}The query selects three fields from Account, keeps only Technology accounts, sorts them by name, and returns at most ten. The result is a List<Account>, and you loop over it like any other list.
Fields you did not select
An inline query only loads the fields named in the SELECT clause. Reading any other field on a returned record throws a System.SObjectException at runtime. Id is the exception, because it is always included. Add a field to the SELECT list before you read it in code.
What the query can return
The same bracket syntax gives different results depending on what you assign it to.
| Assigned to | What you get | When no row matches |
|---|---|---|
| `List<Account>` | All matching records | An empty list |
| `Account` | The single matching record | `QueryException` |
| `Integer` with `SELECT COUNT()` | The number of matching rows | `0` |
A list is the safest choice. Assigning to a single Account throws a QueryException when no row matches, and also when more than one row matches. Query into a list and check isEmpty() before reading the first element.
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];SELECT COUNT() returns an Integer directly. It is cheaper than loading every record and calling size(), because Salesforce does not send the rows back.
How inline queries run
The following diagram shows the steps for a single inline query.
Every execution of a bracketed query counts against the SOQL governor limit for the transaction. A query inside a loop runs once per iteration, so keep queries out of loops. Later chapters cover this limit and the bulk-safe patterns that avoid it.
Common errors
SObjectException: SObject row was retrieved via SOQL without querying the requested field: you read a field that is not in theSELECTlist.QueryException: List has no rows for assignment to SObject: you assigned to a single record and nothing matched.QueryException: List has more than 1 row for assignment to SObject: you assigned to a single record and several rows matched.
Exercise
A method runs Account a = [SELECT Id, Name FROM Account WHERE Name = :searchName];. Name two ways it can throw a QueryException, and rewrite it so neither can happen.
Show answer
It throws if no account matches, and it throws if more than one account matches. Query into a list instead: List<Account> found = [SELECT Id, Name FROM Account WHERE Name = :searchName LIMIT 1]; then read found[0] only after checking !found.isEmpty(). The list never throws for zero or many rows, and LIMIT 1 caps the result at one.
Exercise
Your code runs Account a = [SELECT Id FROM Account LIMIT 1]; and then reads a.Industry. What happens, and how do you fix it?
Show answer
Reading a.Industry throws a System.SObjectException because Industry was not in the SELECT list. Add it: SELECT Id, Industry FROM Account LIMIT 1.