What is Saving & committing in Trigger Terminology

Let me explain this Saving & Committing to Database in Trigger context with a simple example.
Assumption:
I have a trigger on Opportunity, there is a chance that I will re-parent Opportunity from one Account to another Account.

My Trigger code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
trigger understandingBeforeAfterEvent on Opportunity (before update, after update) 
{
    if(Trigger.IsBefore && Trigger.IsUpdate)
    {
        System.debug('Before Update '+Trigger.new);    
        System.debug('-before Update - '+ [Select Id,Name, (Select Id,Name from opportunities) From Account where Id IN (Select AccountId From Opportunity where Id In:Trigger.new)]);
    }
    
    if(Trigger.IsAfter && Trigger.IsUpdate)
    {
       System.debug('After Update '+Trigger.new); 
       System.debug('-After-'+ [Select Id,Name, (Select Id,Name from opportunities) From Account where Id IN (Select AccountId From Opportunity where Id In:Trigger.new)]);

    }
}

Before editing, the state of the Opportunity record is

After editing (I'm going to reparent to a new Account), the state of the opportunity record is

Now, we need to understand how above trigger code snippet executed in the back end by analyzing the debug logs

00:01:16.0 (14407840)|USER_DEBUG|[5]|DEBUG|Before Update (Opportunity:{Id=0066C000005qtgTQAQ, AccountId=0016C00000EkFBXQA3,Name=OpportunityWithAccountInsert}) 
If we observe the line#5 debug results, we can say that in before update event if we try to print Trigger.new then it will hold the latest values.

00:01:16.0 (31832039)|USER_DEBUG|[6]|DEBUG|-before Update - (Account:{Id=0016C00000EkNIpQAN, Name=Hallie})
If we observe the line#6 debug results, we can say that data is just saved as a result, if we try to query from the database by keeping Trigger.new in the Where clause still retrieved the old data.

00:01:16.0 (104264198)|USER_DEBUG|[11]|DEBUG|After Update (Opportunity:{Id=0066C000005qtgTQAQ,AccountId=0016C00000EkFBXQA3,
Name=OpportunityWithAccountInsert})
If we observe the line#11 debug results, in after update event Trigger.new values are same as before update Trigger.new debug statement results.

00:01:16.0 (119078591)|USER_DEBUG|[12]|DEBUG|-After-(Account:{Id=0016C00000EkFBXQA3, Name=ManjuAccount-1})
If we observe the line#12 debug results, we can say that data is just committed to Database as a result, if we try to query from the database by keeping Trigger.new in the Where clause retrieved the new data.

Note: If we observe my trigger code snippet, to query Account records I have used Semi-Join this helped me to eliminate for..lop and holding the AccountId's into Set.

tHiNk gooD and dO thE bEsT.........MANJU NATH 🌝

Comments