You are here:
ApexGuru Antipattern: SOQL with Apex Filter
Executing SOQL queries without a WHERE clause or LIMIT statement and filtering them in Apex retrieves unnecessary data. This process increases memory and CPU usage and can lead to overall system performance and governor limit issues.
Scope
Detection and recommendation
Detection Example
List<Custom_Object__c> records = [
SELECT Id, Name, Category__c, Amount__c, Status__c,
Priority__c, Type__c
FROM Custom_Object__c
];
List<Custom_Object__c> filteredRecords = new List<Custom_Object__c>();
for (Custom_Object__c record : records) {
if (record.Status__c == 'Open' || record.Status__c == 'Pending') {
filteredRecords.add(record);
}
}Recommendation
To minimize data volume and improve query efficiency, avoid postprocessing and filtering in
Apex. Apply filters directly in the SOQL query using WHERE clauses and restrict
results using LIMIT statements. This recommendation prevents Central Processing
Unit (CPU) and memory limit breaches.
List<Custom_Object__c> filteredRecords = [
SELECT Id, Name, Category__c, Amount__c, Status__c,
Priority__c, Type__c
FROM Custom_Object__c
WHERE Status__c = 'Open'
OR Status__c = 'Pending'
];