+ Start a Discussion
sachin shah 27sachin shah 27 

Hi All what is the difference between list soql query and for soql query ?

Best Answer chosen by sachin shah 27
Leo10Leo10
Hi,
SOQL for loops retrieve all sObjects, using efficient chunking with calls to the query and queryMore methods of the SOAP API. Developers should always use a SOQL for loop to process query results that return many records, to avoid the limit on heap size
To provide an example, say each SObject you query occupies on average 2k bytes. Then using option 2 in the question means at most 6M/2k = 3,000 records will cause the total heap size governor limit to be hit. Using option 1 in the question where blocks of 200 records are returned, that governor limit will not be hit with the platform taking care of the chunking for you.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_loops_for_SOQL.htm

Lists can contain sObjects among other types of elements. Lists of sObjects can be used for bulk processing of data.
You can use a list to store sObjects. Lists are useful when working with SOQL queries. SOQL queries return sObject data and this data can be stored in a list of sObjects. Also, you can use lists to perform bulk operations, such as inserting a list of sObjects with one call.​
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_list_sobject.htm

Thank you

All Answers

Leo10Leo10
Hi,
SOQL for loops retrieve all sObjects, using efficient chunking with calls to the query and queryMore methods of the SOAP API. Developers should always use a SOQL for loop to process query results that return many records, to avoid the limit on heap size
To provide an example, say each SObject you query occupies on average 2k bytes. Then using option 2 in the question means at most 6M/2k = 3,000 records will cause the total heap size governor limit to be hit. Using option 1 in the question where blocks of 200 records are returned, that governor limit will not be hit with the platform taking care of the chunking for you.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_loops_for_SOQL.htm

Lists can contain sObjects among other types of elements. Lists of sObjects can be used for bulk processing of data.
You can use a list to store sObjects. Lists are useful when working with SOQL queries. SOQL queries return sObject data and this data can be stored in a list of sObjects. Also, you can use lists to perform bulk operations, such as inserting a list of sObjects with one call.​
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_list_sobject.htm

Thank you
This was selected as the best answer
Rohit B ☁Rohit B ☁
Hi Sachin,
If Leo's ans helped you then please marked it as 'Best Answer' and solved this question.
If you still have any doubt please do let us know.