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
Akshay JuwaAkshay Juwa 

Iterate all the records

Hello Everyone, 

I am new to salesforce developing. I'd like to ask how to iterate all the records that has been queried.

 List<Account> OptOutEmail =[SELECT Id, PersonEmail, Brand__c, CreatedDate, Opt_Out_Preference__c FROM Account WHERE CreatedDate < 2022-08-10T16:00:53.000+0000];

The recods include PersonEmail, Brand__c, CreatedDate, Opt_out_preference.
Best Answer chosen by Akshay Juwa
PriyaPriya (Salesforce Developers) 
Hey Akshay,

You have to use FOR loop to iterate the record. For example :-
 
List<Account> OptOutEmail =[SELECT Id, PersonEmail, Brand__c, CreatedDate, Opt_Out_Preference__c FROM Account WHERE CreatedDate < 2022-08-10T16:00:53.000+0000];

//so in the above statement you may or may not get the records after query. then you need to check the size of the list variable. If the size is more than 1, that means you have got some records in it. Now you need to iterate in a FOR loop supported by Apex.

If(OptOutEmail.size>0){
    
   for(Account a : OptOutEmail ){

     your logic/action
   }

}
 
To learn more about it, you can refer these documents,
1. https://www.levelupsalesforce.com/for-loops-in-salesforce

2. https://www.tutorialandexample.com/salesforce-loops-in-apex

3. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_loops_for_traditional.htm

You can anytime let us know if you need any further clarification/assisatnce.

Kindly do not forget to mark it as the best answer if the information was helpful.

 

Thanks & Regards,

Priya Ranjan