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.
trigger MileageTrigger on Mileage__c (before insert, before update) { User c = [SELECT Id FROM User WHERE mileageid__c = Trigger.new[0].id]; }
trigger MileageTrigger on Mileage__c (before insert, before update) { for(mileage__c m : Trigger.new){ User c = [SELECT Id FROM user WHERE mileageid__c = m.Id]; } }
For more information on governor limits, see Execution Governors and Limits.
Trigger MileageTrigger on Mileage__c (before insert, before update) { Set<ID> ids = Trigger.newMap.keySet(); List<User> c = [SELECT Id FROM user WHERE mileageid__c in :ids]; }
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.