Sub topic 2
Running SOQL inline in Apex
This chapter assumes you can read basic Apex (variables, lists, loops, classes), know what objects, fields, and relationships are, and can run Apex in the Developer Console or an IDE. It covers how a query is written inside Apex code, what it returns, and what goes wrong when you treat the result carelessly.
What an inline query is
SOQL (Salesforce Object Query Language) reads records from your org. In Apex you can write a query directly in your code by putting it in square brackets. This is called an inline, or static, query. The compiler parses it along with the rest of the class.
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 has two required parts:
SELECTlists the fields to return, separated by commas.FROMnames one object to read.
The WHERE, ORDER BY, and LIMIT clauses are optional. Later chapters cover them in detail. Here they only make the example realistic.
SOQL differs from SQL in a few ways that matter right away:
- There is no
SELECT *. You must name every field you want. - You query one object at a time. There are no joins. Related records are reached through relationship names, which a later chapter covers.
- Field and object names are not case sensitive, but string comparisons in filters follow the field's own rules.
- Keywords such as
SELECTandFROMare not case sensitive either. Most teams write them in uppercase.
Compile-time checking
Because the query is part of the code, Salesforce checks it when you save the class. If you misspell Industy, name an object that does not exist, or select a field that does not exist, the save fails. You find the error before the code runs.
The three shapes of a result
What the query returns depends on what you assign it to. The same bracketed syntax can produce a list, a single record, or a number.
| Assigned to | Example | Behavior |
|---|---|---|
| `List<sObject>` | `List<Account> a = [SELECT Id FROM Account];` | Always works. An empty list means no rows matched. |
| A single sObject | `Account a = [SELECT Id FROM Account LIMIT 1];` | Throws `QueryException` if zero rows or more than one row match. |
| `Integer` | `Integer n = [SELECT COUNT() FROM Account];` | Returns the number of matching rows. |
You can also pass a query straight into a Map constructor. The map is keyed by record Id, which is handy for lookups later.
Map<Id, Account> byId = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 50]
);Why a list is the safe default
Assigning a query to a single record looks tidy, but it fails when the data is not what you expected. Zero matching rows throws a QueryException with the message "List has no rows for assignment to SObject". Two or more rows also throws, with "List has more than 1 row".
Query into a list and check it instead:
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];Adding LIMIT 1 to a single-record query removes the "more than one row" failure. It does not remove the "no rows" failure. Use the single-record form only when the record must exist and its absence should stop the code, such as a record you created a few lines earlier.
SELECT COUNT() is a special form. It has no field list and returns an Integer directly. It counts rows without loading them, so it uses no heap memory. It still counts as one query against your limits.
Fields you did not select are not available
An sObject returned from a query holds only the fields you selected, plus the record Id. The Id comes back even if you leave it out of the SELECT list. Reading any other field you did not select throws an SObjectException.
List<Account> accts = [SELECT Id, Name FROM Account LIMIT 1];
if (!accts.isEmpty()) {
try {
System.debug(accts[0].Industry);
} catch (SObjectException e) {
System.debug('Not queried: ' + e.getMessage());
}
}The message reads "SObject row was retrieved via SOQL without querying the requested field: Account.Industry". This is one of the most common errors for new Apex developers. The fix is to add the field to the SELECT list.
Two related details:
- Writing to a field you did not query is allowed. Only reading it fails. This means you can build an update on a queried record, but you cannot inspect fields you skipped.
- A field that was queried but holds no value returns
null. Anullresult and a "not queried" error are different things, so do not guard against one when you mean the other.
Where inline queries can appear
The square-bracket form works anywhere Apex accepts an expression. The common placements are:
- On the right side of an assignment, as in the examples above.
- As the collection in a
forloop. This is a SOQL for loop, which behaves differently and has its own chapter. - Directly inside a method call or constructor, such as
new Map<Id, Account>([...]). - Inside a condition, for instance
if ([SELECT COUNT() FROM Account] > 0).
You can write the query across several lines, as the examples do. Whitespace and line breaks inside the brackets have no effect.
Watching the query count
Every inline query that runs counts toward a governor limit. Governor limits are per-transaction caps that Salesforce enforces so that no one customer's code can starve a shared server. A synchronous transaction may run at most 100 SOQL queries. An asynchronous one, such as a batch or queueable job, may run 200. A later chapter explains these limits in full. For now, know that you can read your usage at any point with the Limits class.
List<Account> accts = [SELECT Id, Name, Industry FROM Account LIMIT 5];
System.debug('Queries used: ' + Limits.getQueries()
+ ' of ' + Limits.getLimitQueries());Run this in the Developer Console as anonymous Apex and open the debug log. You should see "Queries used: 1 of 100". The count is per query execution, not per row returned. A query that returns 5,000 rows and one that returns none each use one query.
Common mistakes in inline queries
- Assigning to a single sObject without handling the case where no row exists.
- Reading a field that is not in the
SELECTlist. - Expecting
SELECT *to exist. - Putting a query in a loop body because it was easy to write there.
- Assuming
LIMIT 1makes a single-record assignment safe. It only prevents the multiple-row error.
Exercise
This code runs on a record you did not create. It throws an exception on the second line, not on the first. What is the exception, and how do you fix it? Account a = [SELECT Id, Name FROM Account LIMIT 1]; System.debug(a.Industry);
Show answer
The second line throws a System.SObjectException, because Industry was not included in the SELECT list, so the field was never loaded. Fix it by adding the field: SELECT Id, Name, Industry FROM Account LIMIT 1. The first line can also throw a QueryException if the org has no accounts, so a safer version queries into a List<Account> and checks isEmpty() before reading element 0.
Exercise
You need only the number of Contact records in the org, and you do not need to read any of them. Which inline query is the most direct, and what type does it return?
Show answer
Integer total = [SELECT COUNT() FROM Contact]; It returns an Integer and does not load the records into heap memory. It still uses one of your SOQL queries for the transaction.