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
sachin kadian 5sachin kadian 5 

What to use 2 queries or for loop?

Hi,

I have one situation in my code where i need a list or Map of records as well as sum of a fields from them. What is the best way to achieve this? i can think 2 ways
1) Use 1 SOQL query to get the Map of records and 1 aggregate query to get the sum of field OR
2) Use 1 SOQL query only to get the record, the loop through them and get the some of field using some variable

In approach first, i think i will have to use 1 extra query and in 2nd approrach, if number of records are more, i could take longer time. 
I am confused which approach i should use. Any suggestions would be great. 

Thanks,
piyush parmarpiyush parmar
Hi Sachin,

If you choose option 
1) You have to write 1 SOQL query & Aggregation query 
& option 
2) You have to write only 1 SOQL query

Go with option 1, As first option heap size less than second option & tale less Apex CPU time.

Perfomace wise option 1 is better.
Lalit Karamchandani 27Lalit Karamchandani 27
HI sachin kadian 5 
1) Use 1 SOQL query to get the Map of records and 1 aggregate query to get the sum of field OR that way is best
https://developer.salesforce.com/forums/?id=906F0000000909tIAA
you can also see that code