Sub topic 2
Handling Query Results Safely
Assume you know basic Apex collections, loops, and Salesforce relationships. Query results can be empty, contain many rows, or return summary values. Handle each shape deliberately.
Handling query results safely
A query assigned to a list returns an empty list when no records match. A query assigned to one sObject throws a QueryException when no record matches.
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Name = 'No Such Account'
LIMIT 1
];
if (!accounts.isEmpty()) {
System.debug(accounts[0].Name);
}
Integer total = [SELECT COUNT() FROM Account];
System.debug('Accounts: ' + total);Date literals and date filters
SOQL date literals express relative periods without calculating dates in Apex. Common examples include TODAY, THISMONTH, and LASTN_DAYS:30.
List<Account> recent = [
SELECT Id, Name
FROM Account
WHERE CreatedDate = LAST_N_DAYS:30
];
DateTime cutoff = System.now().addDays(-30);
List<Account> alsoRecent = [
SELECT Id, Name
FROM Account
WHERE CreatedDate >= :cutoff
];Querying related records
A child-to-parent query uses dot notation. A parent-to-child query uses the child relationship name and a subquery.
List<Contact> contacts = [
SELECT LastName, Account.Name
FROM Contact
WHERE Account.Industry = 'Technology'
];
List<Account> accounts = [
SELECT Name, (SELECT LastName FROM Contacts)
FROM Account
WHERE Industry = 'Technology'
];Aggregate functions and GROUP BY
Aggregate queries return AggregateResult rows instead of sObjects. Query aliases become keys for the get method.
List<AggregateResult> rows = [
SELECT Industry industry, COUNT(Id) total
FROM Account
WHERE Industry != null
GROUP BY Industry
];
for (AggregateResult row : rows) {
String industry = (String) row.get('industry');
Integer total = (Integer) row.get('total');
System.debug(industry + ': ' + total);
}Understanding SOQL governor limits
Salesforce limits SOQL statements per transaction. The usual limits are 100 synchronous queries and 200 asynchronous queries. A query inside a loop can exceed those limits.
Collect related IDs, query once with IN, and use a map. For large result sets, a SOQL for loop processes records in batches.
Exercise
Why should a query for an optional record usually be assigned to a List<Account>?
Show answer
A list safely represents zero or more rows, while single-record assignment throws a QueryException when no row matches.