bulkify trigger in salesforce

While writing a trigger logic, the deadly thing a developer would do is not bulkify the trigger code. After writing the trigger logic, a developer unit tests the scenario by manually creating record or updating a record and for that moment the trigger works absolutely fine.
The code is written considering only one record would invoke the trigger. But, in reality this may not be the case. Your trigger would very well be invoked by many records at a time. Many Records inserted/updated through data loader can invoke your trigger at a time. Because of this, we must make sure our trigger is bulkified. In other words bulkifying trigger means the trigger is good enough to run the same logic on each and every record that has invoked the trigger at that moment.
Let me give you an example how a trigger is not bulkified:
The above trigger has been written to update the account field "type" with a value 'prospect' if its annual revenue is greater than 1000. After activating the trigger and testing for one account record in salesforce UI it works fine. It updates the type to 'prospecting' if the account annual revenue is greater than 1000.
But, if we update number of account records from data loader the same trigger fails, it only updates the account which is first in the csv file. It does not give any error or lets you know that it is not bulkified.
So how do we solve this? How do we bulkify trigger?
If you have noticed, we have compared the record from trigger.new[0]. In trigger, all the records which invoke that trigger are stored in a list "trigger.new" hence we will have to make sure all the records are taken into consideration to implement the logic.
Following trigger has been bulkified and will work properly for both UI and data loader records,

This was a very simple example where trigger is bulkified, for complex scenarios you can use maps, sets and list appropriately to bulkify the trigger.

1 comment: