Share Your Experience With Others

Trigger Context Variables (Trigger.New,Trigger.newMap,Trigger.old,Trigger.oldMap)

Trigger.new : Returns a list, which are ordered. If you have multiple loops over each item the trigger is operating on, the list returned by Trigger.new may be the better.

Trigger.newMap : Returns a map , which are unordered. if you have an ID of an object you need to do something with, using the map makes more sense as you can use newMap.get().
Otherwise you’d have to loop over all the elements in Trigger.new and look for a matching ID.

Difference between Trigger.new and Trigger.newMap:

Suppose you have a custom object Custom_obj__c

Trigger.New means it is a List<Custom_obj__c>
and
Trigger.NewMap means it is a Map<Id, Custom_obj__c>

In before insert context your Trigger.newMap will always be null because in before context records are not submitted to the database, so the Id is not generated yet. That’s why in before insert we don’t use Trigger.newMap But in After insert, Id is generated so we can use Trigger.newMap.

In case of before and after update, the Id has already been generated in the insert event. So we can use Trigger.newMap in before and after update.

Suppose Your code is like this in after insert case:

For example we have 200 accounts we are using Trigger.new to get the inserted AccountIds

So the for loop will run 200 times to add Account IDs to the set.

set<Id> accIds = new set<Id>();
for(Account acc : Trigger.new)
{
accIds.add(acc.id);
}
//query the contact records now from currently processed Account Ids
List<Contact> lstContact = [select id from contact where Accountid in : accIds];

Now When we use Trigger.newMap

Now we have no need a for loop because all the IDs are in Trigger.newMap.Keyset().

List<Contact> lstContact = [select id from contact where Accountid in : Trigger.newmap.Keyset()];

Execution time will be reduced using Trigger.newMap in comparison to Trigger.new.

Trigger.old : Returns a list of the old versions of the sObject records. Note that this sObject list is only available in update and delete triggers.

Trigger.oldMap : A map of IDs to the old versions of the sObject records.Note that this map is only available in the update and delete triggers.

Suppose you have a custom object Custom_obj__c

Trigger.old means it is a List<Custom_obj__c>
and
Trigger.oldMap means it is a map<Id, Custom_obj__c>

Available Values of context variables in before and after events:——————————–

Before insert  ==>Trigger.new.

After insert    ==>Trigger.new,Trigger.newMap.

Before update ==>Trigger.new,Trigger.newMap,Trigger.old,Trigger.oldMap.

After update   ==>Trigger.new,Trigger.newMap,Trigger.old,Trigger.oldMap.

Before delete   ==>Trigger.old,Trigger.oldMap.

After delete     ==>Trigger.old,Trigger.oldMap.

After undelete ==>Trigger.new,Trigger.newMap.

Learn more in details in the below video:

Leave a comment