Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.
Trigger and Bulk Request Best Practices
A common development pitfall is the assumption that trigger invocations never include more than one record. Apex triggers are optimized to operate in bulk, which, by definition, requires developers to write logic that supports bulk operations.
1trigger MileageTrigger on Mileage__c (before insert, before update) {
2 User c = [SELECT Id FROM User WHERE mileageid__c = :Trigger.new[0].id];
3}1trigger MileageTrigger on Mileage__c (before insert, before update) {
2 for(mileage__c m : Trigger.new){
3 User c = [SELECT Id FROM user WHERE mileageid__c = :m.Id];
4 }
5}For more information on governor limits, see Execution Governors and Limits.
1Trigger MileageTrigger on Mileage__c (before update) {
2 Set<ID> ids = Trigger.newMap.keySet();
3 List<User> c = [SELECT Id FROM user WHERE mileageid__c in :ids];
4}This pattern respects the bulk nature of the trigger by passing the Trigger.new collection to a set, then using the set in a single SOQL query. This pattern captures all incoming records within the request while limiting the number of SOQL queries.
Best Practices for Designing Bulk Programs
- Minimize the number of data manipulation language (DML) operations by adding records to collections and performing DML operations against these collections.
- Minimize the number of SOQL statements by preprocessing records and generating sets, which can be placed in single SOQL statement used with the IN clause.