0

I have the following snippets: first example is not bulkified and the second it is bulkified. I'm not sure why the second snippet it's bulkified and will not hit any governor limits while the first example will hit governon limits.

This code is not bulkified and will go over the 150 DML statements limit:

for (Opportunity opp : Trigger.new) {
Task t = new Task();
t.Name = 'Give your prospect a free t-shirt';
t.WhatId = opp.Id;
insert t;
}

Please correct me if i'm wrong, the code does this things: 1. For every new opportunity 2. It will create a task 3. Give the name of the task to the 'Give your prospect a free t-shirt' 4. Associate the id of the task to the id of the opportunity 5. Insert the tasks   This example is bulkified, I'm not sure why.

List<Task> taskList = new List<Task>();

for (Opportunity opp : Trigger.new)
  {
    Task t = new Task();
    t.Name = 'Give your prospect a free t-shirt';
    t.WhatId = opp.Id;
    taskList.add(t);
  }
insert taskList; 
  1. It creates an empty list called taskList
  2. For every new opportunity
  3. Creates new Task
  4. Give the name of the to : 'Give your prospect a free t-shirt';
  5. Associate the id of the task to the opportunity
  6. The task is added to the empty list: taskList
  7. Insert the list, but why outside the loop though ?   I'm new in programming and i want to learn, thank you! :)
3

So As you know that we have a limit of 150 DML in a single transaction.

For example in this code

for (Opportunity opp : Trigger.new) {
   Task t = new Task();
   t.Name = 'Give your prospect a free t-shirt';
   t.WhatId = opp.Id;
   insert t;
}

Insert DML inside the for loop. Suppose if you are inserting 200 Opportunity using data loader. Then Trigger.New will have 200 records means the above for loop will iterate over 200 times and since the insert DML inside for loop. It will execute over 200 times right?

So in this scenario, you will get the 150 DML limit issue.

Now the bulkified code

List<Task> taskList = new List<Task>();

for (Opportunity opp : Trigger.new)
{
    Task t = new Task();
    t.Name = 'Give your prospect a free t-shirt';
    t.WhatId = opp.Id;
    taskList.add(t);
}
insert taskList; 

Now here suppose you are inserting 200 Opportunity records from data loader. SO in Trigger.New will have 200 records and for loop will iterate over 200 times and it will add all the task in a list. (no DML till now)

Now once the for loop finished, all the 200 task added to a list.

And after that only 1 DML will be required to insert all the 200 Tasks records.

So this way we handle the Governor limits

  • @Franken, if it helped you mark it as answer – RedDevil Feb 28 '18 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.