I have a question on apex triggers. Trigger.new is the list of new records that can be inserted and trigger.old is the list of old records or the existing records in the database. If we are doing an after update trigger on an account object, why do we loop through trigger.new instead of trigger.old????
Trigger.new will hold values which are newly changed but
Trigger.old will hold values from database.
Lets say from UI you changed account-fieldA from '20' to '30' .So if you loop on
Trigger.old and if you are expecting some logic which checks if
30 then run some function it would fail. Because
Trigger.old will hold value from DB and as the transaction is not committed yet, the value
30 is not yet committed to DB.
So we use trigger.new to loop in expecting all the values which are changed from UI will be available there. And
trigger.old is used to compare if the value is changed then proceed running the trigger.