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
Fares AlsyoufiFares Alsyoufi 

Beginner question - Why do we run this loop in almost every trigger?


I'm new to Apex programming and I noticed this trend in building Apex triggers. Almost every trigger I saw include this code: 
//Create a set that includes all the account ids
Set<Id> AccIds=new set<Id>();
/*Go through a list of accounts and assign Ids (generated in the set) to all account rows in the list*\
//Also why do you always use method?

A detailed explanation would be highly appericiated?

Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello Fares, is a context variable.

To access the records that caused the trigger to fire, use context variables. For example, Trigger.New contains all the records that were inserted in insert or update triggers. Trigger.Old provides the old version of sObjects before they were updated in update triggers, or a list of deleted sObjects in delete triggers. Triggers can fire when one record is inserted, or when many records are inserted in bulk via the API or Apex. Therefore, context variables, such as Trigger.New, can contain only one record or multiple records. You can iterate over Trigger.New to get each individual sObject.

In your example this code would be in a trigger for the Account sObject. As context variables are dependent of the context, its values can have different types of sObject. Let's say that you creates a trigger for the Contact sObject, then the code would be something like:
for (Contact con : {
     // do something

I strongly recommend you this reading:

If you have knowledge in other programming language such as C# or Java, you might find this helpful as well: (http://​

Hope to have helped!


Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.
Fares AlsyoufiFares Alsyoufi
Hi Zuinglio,

Thanks for your quick and elaborative response. One peice I'm still not getting though. Why are we creating the Set <ID> of accounts ids and assinging them to the a records in list (line 2 and 6)? 

Thanks again,