Loading
Scalability
ApexGuru Antipattern: Redundant SOQL

ApexGuru Antipattern: Redundant SOQL

Executing multiple SOQL queries on the same sObject with identical or nearly identical filter conditions creates inefficiencies. This practice wastes governor limits and increases transaction time because it requires more database round-trips. Processing separate query responses wastes CPU time and heap space.

Scope

Detection and recommendation

Detection Example

//Apex
// Bad: Two round-trips to the database
User userA = [SELECT Id FROM User WHERE ContactId = :idA];
User userB = [SELECT Id FROM User WHERE ContactId = :idB];

Recommendation

Merge these queries into fewer SOQL statements, followed by in-memory filtering in Apex. Query all records at the same time and map them for easy access. This scales regardless of whether you need 2 records or 200.

//Apex
// Good: One round-trip using a Set and Map
Set<Id> contactIds = new Set<Id>{ idA, idB };
// 1. Bulk Query
List<User> users = [SELECT Id, ContactId FROM User WHERE ContactId IN :contactIds];
// 2. In-Memory Organization (The Map Pattern)
Map<Id, User> userMap = new Map<Id, User>();
for(User u : users) {
    userMap.put(u.ContactId, u);
}
// 3. Retrieve efficiently
User userA = userMap.get(idA);
User userB = userMap.get(idB);
 
Indlæser
Salesforce Help | Article