Sub topic 3
SOQL for Loops for Large Result Sets
Assume you know basic Apex collections and Salesforce relationships. This chapter focuses on writing queries that remain safe and efficient as data volume grows.
SOQL for Loops for Large Result Sets
A SOQL for loop retrieves records in batches instead of placing the entire result in one list. This reduces heap usage when many records match.
Integer processed = 0;
for (Account account : [
SELECT Id, Name
FROM Account
WHERE Industry = 'Technology'
]) {
processed++;
}
System.debug('Processed ' + processed + ' accounts');The loop still counts against query and row governor limits. It only changes how records are loaded into memory.
Bulk-Safe Query Patterns
Never query inside a loop. Collect related IDs, query once, and use a map for lookups.
Set<Id> accountIds = new Set<Id>();
for (Contact contact : contacts) {
if (contact.AccountId != null) {
accountIds.add(contact.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);This pattern keeps the number of queries constant even when contacts contains many records.
Enforcing Sharing and Field-Level Security
with sharing applies record-sharing rules to a class, but it does not by itself enforce field-level security. Add WITH USER_MODE when a query should honor the current user's sharing, object permissions, and field permissions.
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Industry = 'Technology'
WITH USER_MODE
];Dynamic SOQL and Preventing Injection
Use bind variables or Database.queryWithBinds() for user-provided values. Allowlist any dynamic field or object names because identifiers cannot be bound.
String industry = 'Energy';
String soql = 'SELECT Id, Name FROM Account WHERE Industry = :industry';
List<Account> accounts = Database.queryWithBinds(
soql,
new Map<String, Object>{ 'industry' => industry },
AccessLevel.USER_MODE
);If concatenation is unavoidable, escape quoted values with String.escapeSingleQuotes().
Testing Code That Runs Queries
Tests should create their own records and assert the query result. Do not depend on existing organization data.
@isTest
private class AccountQueryTest {
@isTest
static void findsTechnologyAccounts() {
insert new Account(Name = 'Test Tech', Industry = 'Technology');
List<Account> result = [
SELECT Id, Name FROM Account WHERE Industry = 'Technology'
];
Assert.areEqual(1, result.size());
Assert.areEqual('Test Tech', result[0].Name);
}
}Query Selectivity and Performance
A selective query filters to a small portion of the table. Use indexed fields such as Id, lookup fields, and often Name or audit fields. Avoid leading-wildcard searches and broad queries without a WHERE clause. Query only the fields you need, then use Query Plan in Developer Console or an IDE to inspect performance.
Exercise
Why is a SOQL for loop not enough to fix a query inside an Apex loop?
Show answer
It controls result loading, but the query inside the outer loop still consumes a query limit for every record. Move the query outside the loop and use a collection of IDs.