1

I have seen way of querying in many ways but does that really make a difference or its just a way of coding

List<CustomObj__c> CustObj = new List<CustomObj__c>();
CustObj = [Select id, Name, CustField1__c, CustField2__c from CustomObj__c];

And

for(CustomObj__c i : Select id, Name, CustField1__c, CustField2__c from CustomObj__c){}

Is there a difference or just a way of writing a code.

0

2 Answers 2

5

There is a nice documentation about your question. Some quotes from there:

SOQL for loops differ from standard SOQL statements because of the method they use to retrieve sObjects. While the standard queries discussed in SOQL and SOSL Queries can retrieve either the count of a query or a number of object records, 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.

Note that queries including an aggregate function don't support queryMore. A run-time exception occurs if you use a query containing an aggregate function that returns more than 2,000 rows in a for loop.

1

The list object will be in heap till the span of the object in the program and another query which is written in for loop will dereference after the loop span completes.

Here you can use the query result throughout the program(considering object span) and the query result of loop will not be used outside the loop and you have to query once again to get the result.

Not the answer you're looking for? Browse other questions tagged .