Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Is the order of records in the Trigger.new list the same in before and after trigger?

Can I rely on the assumption that: on before r1 in the Trigger.new list on the 1st place; on after r1 in the Trigger.new list on the 1st place; Thanks

share|improve this question
2  
Even if they are in the same order though, there is no reason to ever need for them to be. –  dphil May 19 at 14:14
4  
I think you would be safer using the maps provided. –  Mike Chale May 19 at 14:24

4 Answers 4

up vote 5 down vote accepted

No, you should not rely on the order of records in Trigger.new and Trigger.old. Use Trigger.newMap and Trigger.oldMap instead.

It's a better practice to use Trigger.newMap and Trigger.oldMap because you can't assume that directly querying the Trigger.new and Trigger.old lists will return the same number of records in the same order. Even though these lists are sorted by ID, external operations might change the number of records that are returned and make parallel list processing dangerous.

Source: http://developer.force.com/cookbook/recipe/comparing-queries-against-trigger-old-and-trigger-new

share|improve this answer

I would say yes since the triggers are associated with the list of records and not as a result of an actual database query. Similar to the database.saveresult where the records are returned in the same order as they are inserted.

I do not have any hard documentation on this but I would bet it is a good assumption..

share|improve this answer

In a trigger records are sorted by Salesforce Id.

So, In case of insert you will get same order throughout the process. Also records insert in order they are inserted in list so first record will get the least id and last one will get greatest Id.

I will not recommend to rely on that order. As it will require a complex design to function properly with different trigger event. However order will be same in after and before operations.

share|improve this answer

In addition to the other valuable remarks by other respondents, records in a before trigger that fail validation rules or otherwise have an addError() method applied to them won't even appear in the after trigger's Trigger.new variable. Thus, the size of the lists may not be equal, before vs after.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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