Queries live in selectors
Every query in this project sits in a selector class named after the object it reads. Triggers, services and controllers call ReferralSelector.openForCoordinator(...) and never write SOQL themselves. The reasons are practical: one place to review field and sharing behaviour, one place to add an index or a field, and a service that can be tested without worrying about what it selects.
Reading as the user
The default for anything a person triggers is WITH USER_MODE. It enforces object permissions, field-level security and sharing for the running user, in the main query and in any subquery. That is what keeps a coordinator from seeing another region’s referral even if a developer forgets a filter.
public inherited sharing class ReferralSelector {
public static List<Referral__c> byIds(Set<Id> ids) {
return [
SELECT Id, Name, OwnerId, Region__c, Status__c, Priority__c, Assigned_Coordinator__c
FROM Referral__c
WHERE Id IN :ids
WITH USER_MODE
];
}
/** One coordinator's open referrals: parent fields through relationships, plus the latest note. */
public static List<Referral__c> openForCoordinator(Id coordinatorId, Integer maxRows) {
Set<String> closed = ReferralStatus.CLOSED;
return [
SELECT Id, Name, Status__c, Priority__c, Region__c, Routed_On__c,
Patient__r.Name, Referring_Clinic__r.Name,
(SELECT Body__c FROM Referral_Notes__r ORDER BY CreatedDate DESC LIMIT 1)
FROM Referral__c
WHERE Assigned_Coordinator__c = :coordinatorId AND Status__c NOT IN :closed
WITH USER_MODE
ORDER BY Priority__c ASC, Routed_On__c ASC
LIMIT :maxRows
];
}
}What each part is doing:
- Bind variables (
:coordinatorId,:closed,:maxRows) keep values out of the query text. For dynamic SOQL the equivalent isDatabase.queryWithBinds(query, binds, AccessLevel.USER_MODE), never string concatenation. - Relationship queries walk up (
Patient__r.Name) and down (theReferral_Notes__rsubquery) in a single round trip. The subquery counts toward the same query, so there is one SOQL statement, not one per referral. ORDER BY Priority__csorts a picklist by its defined order. Urgent is declared first, so it comes first, and no CASE logic is needed.LIMIT :maxRowsis a real cap, passed down from the caller, never a hope that the result set is small.
Aggregates for the board
The board header shows how many open referrals are urgent. Counting rows in Apex would pull every record into the heap; the database can do it with GROUP BY.
public static Map<String, Integer> openCountsByPriority(Id coordinatorId) {
Set<String> closed = ReferralStatus.CLOSED;
Map<String, Integer> counts = new Map<String, Integer>();
for (AggregateResult ar : [
SELECT Priority__c priority, COUNT(Id) total
FROM Referral__c
WHERE Assigned_Coordinator__c = :coordinatorId AND Status__c NOT IN :closed
WITH USER_MODE
GROUP BY Priority__c
]) {
counts.put((String) ar.get('priority'), (Integer) ar.get('total'));
}
return counts;
}Aliases (priority, total) are how an AggregateResult is read back. The clause order is fixed: WHERE, then WITH, then GROUP BY.
Setup data and the routing queries
The routing rule needs two things an intake agent has no business reading: who is in a coordinator group, and how many referrals each coordinator carries across the whole org. Both are system data, so these selectors say so out loud with WITH SYSTEM_MODE and keep the system-level access as narrow as possible.
public inherited sharing class CoordinatorSelector {
/** Region -> Id of its coordinator public group. The mapping is custom metadata: no SOQL to read it. */
public static Map<String, Id> groupIdsByRegion(Set<String> regions) {
Map<String, String> nameByRegion = new Map<String, String>();
for (String region : regions) {
Referral_Routing__mdt cfg = Referral_Routing__mdt.getInstance(region);
if (cfg != null) nameByRegion.put(region, cfg.Coordinator_Group__c);
}
Set<String> names = new Set<String>(nameByRegion.values());
Map<String, Id> idByName = new Map<String, Id>();
for (Group g : [SELECT Id, DeveloperName FROM Group
WHERE Type = 'Regular' AND DeveloperName IN :names WITH SYSTEM_MODE]) {
idByName.put(g.DeveloperName, g.Id);
}
Map<String, Id> result = new Map<String, Id>();
for (String region : nameByRegion.keySet()) {
Id groupId = idByName.get(nameByRegion.get(region));
if (groupId != null) result.put(region, groupId);
}
return result;
}
} /** Region -> active users in its group. Direct members only; nested groups are out of scope here. */
public static Map<String, List<Id>> userIdsByRegion(Set<String> regions) {
Map<String, Id> groupIds = groupIdsByRegion(regions);
Set<Id> groupIdSet = new Set<Id>(groupIds.values());
Map<Id, List<Id>> memberIdsByGroup = new Map<Id, List<Id>>();
Set<Id> candidates = new Set<Id>();
for (GroupMember gm : [SELECT GroupId, UserOrGroupId FROM GroupMember
WHERE GroupId IN :groupIdSet WITH SYSTEM_MODE]) {
if (gm.UserOrGroupId.getSObjectType() != User.SObjectType) continue;
candidates.add(gm.UserOrGroupId);
if (!memberIdsByGroup.containsKey(gm.GroupId)) memberIdsByGroup.put(gm.GroupId, new List<Id>());
memberIdsByGroup.get(gm.GroupId).add(gm.UserOrGroupId);
}
Set<Id> active = new Map<Id, User>(
[SELECT Id FROM User WHERE Id IN :candidates AND IsActive = true WITH SYSTEM_MODE]
).keySet();
Map<String, List<Id>> result = new Map<String, List<Id>>();
for (String region : groupIds.keySet()) {
List<Id> users = new List<Id>();
for (Id userId : memberIdsByGroup.get(groupIds.get(region)) ?? new List<Id>()) {
if (active.contains(userId)) users.add(userId);
}
result.put(region, users);
}
return result;
}The workload count is the one place where a query must see every referral, including ones the running user cannot open. It returns counts only, never rows, and the without sharing is confined to a private inner class so nothing else in the file inherits it.
public inherited sharing class ReferralWorkload {
/** Open referrals per coordinator across the org. Every requested Id is present, with 0 when idle. */
public static Map<Id, Integer> openCounts(Set<Id> coordinatorIds) {
return new Counter().run(coordinatorIds);
}
// Counts only: the routing rule must see the whole org's load, not what the intake user can open.
private without sharing class Counter {
public Map<Id, Integer> run(Set<Id> coordinatorIds) {
Map<Id, Integer> counts = new Map<Id, Integer>();
for (Id coordinatorId : coordinatorIds) counts.put(coordinatorId, 0);
Set<String> closed = ReferralStatus.CLOSED;
for (AggregateResult ar : [
SELECT Assigned_Coordinator__c coordinator, COUNT(Id) total
FROM Referral__c
WHERE Assigned_Coordinator__c IN :coordinatorIds AND Status__c NOT IN :closed
WITH SYSTEM_MODE
GROUP BY Assigned_Coordinator__c
]) {
counts.put((Id) ar.get('coordinator'), (Integer) ar.get('total'));
}
return counts;
}
}
}SOQL in a loop
The most common way a trigger works in a test and fails in production. Suppose referrals are only accepted from active partner clinics (a checkbox, Is_Active_Partner__c, I added to Account for this example).
// One query per record. A bulk load of 200 referrals runs 200 queries,
// and the 101st throws System.LimitException: Too many SOQL queries: 101.
for (Referral__c r : referrals) {
Account clinic = [SELECT Is_Active_Partner__c FROM Account WHERE Id = :r.Referring_Clinic__c];
if (!clinic.Is_Active_Partner__c) {
r.Referring_Clinic__c.addError('This clinic is not an active partner.');
}
}The fix is always the same shape: collect the Ids, query once into a map, then loop over the map. The number of queries no longer depends on the number of records.
Set<Id> clinicIds = new Set<Id>();
for (Referral__c r : referrals) {
if (r.Referring_Clinic__c != null) clinicIds.add(r.Referring_Clinic__c);
}
Map<Id, Account> clinics = new Map<Id, Account>(
[SELECT Id, Is_Active_Partner__c FROM Account WHERE Id IN :clinicIds WITH USER_MODE]
); // one query, however many referrals
for (Referral__c r : referrals) {
Account clinic = clinics.get(r.Referring_Clinic__c);
if (clinic != null && !clinic.Is_Active_Partner__c) {
r.Referring_Clinic__c.addError('This clinic is not an active partner.');
}
}The same shape fixes DML in a loop: add to a list inside the loop, run one insert, update or delete after it.
Governor limits worth remembering
| Limit (per transaction) | Synchronous | Asynchronous (batch, queueable) |
|---|---|---|
| SOQL queries | 100 | 200 |
| Rows returned by SOQL | 50,000 | 50,000 |
| DML statements | 150 | 150 |
| Rows processed by DML | 10,000 | 10,000 |
| CPU time | 10 seconds | 60 seconds |
How this project stays inside them:
- The routing rule runs four queries for a transaction however many referrals it contains. The sharing sync adds two more. A test later asserts this with
Limits.getQueries(). - A
for (Referral__c r : [SELECT ...])loop (a SOQL for loop) fetches rows in chunks of 200 instead of loading the whole result into the heap. The recalculation batch goes further and uses aQueryLocator, which streams the rows in scopes. - Selectivity. The coordinator query filters on a lookup field, and lookups are indexed automatically, so the optimiser can start from that index.
Status__c NOT IN (...)on its own is not selective, because a negative filter cannot use an index well, so it only ever narrows down a result the index has already made small. IfRegion__cbecomes a filter on a large table, it is a candidate for a custom index. As a rule of thumb the optimiser wants a filter that cuts the table to a small fraction of its rows; the Large Data Volumes guide has the exact thresholds.