function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
renu anamalla 9renu anamalla 9 

before insert and after insert differnece and give me example

before insert and after insert differnece and  give me example?
Vasani ParthVasani Parth
Hi Renu - Welcome to this vibrant community.

Here's the break down from my experience :

Before
  • I'm updating the record that's being updated/inserted - or doing something based on the record being modified
  • Examples: Set value of a pick list based on criteria. Send apex e-mail based on the record updated/inserted

After
  • In after you can query for the updated field here.
  • Examples: Create a task of an Opportunity that's been edited, Change a look up value on a related record from the Opportunity being edited
  • The main thing to consider is that the Before happens before the data has been written to the server. This means you can modify the records in "Trigger.new" without having to call a separate "Update." This is ideal if you want to modify data in the records within Trigger.new
  • After happens after the data has been written to the server. This is important when wanting to create additional related records (Can't create a related record until AFTER the parent has been inserted).
Please mark this as the best answer if this helps
DeveloperSudDeveloperSud
Hi Renu,
Vasani has explained the difference very nicely.you can refer the below two codes to spot the difference between before and after insert triggers.
***Before Insert Trigger***
trigger HelloWorldTrigger on Account (before insert) {
for(Account a : Trigger.New)
a.Hello__c = 'World';
}

****After Insert Trigger***
trigger HelloWorldTrigger on Account (after insert) {
    List<Account> accList = new List<Account>();
    for(Account a : Trigger.New){
        Account acc = new Account(id = a.id, Hello__c = 'World');
        accList.add(acc);
    }
    if(accList.size()>0)
    update accList;
}


You can follow the below link to know more on when to use before or after insert trigger.
http://www.sfdc99.com/2014/01/25/use-vs-triggers/
Thanks!!!
SalesFORCE_enFORCErSalesFORCE_enFORCEr
Before insert - Record is not commited to the database so you will not get the record id and you can change anything on the record without actually querying it from the database.
After insert -  Record is commited to the database so if you want to update it, you need to query it from the database.