Posts

Showing posts with the label for loop

Salesforce Fact #938 | SOQL for loop limit error

Image
Have you encountered the error:  System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop. The error is encountered when SOQL For loop is used on a parent to child SOQL and the child record list contains 200 or more records. To resolve this, we need to run a separate for loop on the child records. Attached are the screenshots.

Salesforce Fact #753 | Save one for loop using clone() method

Image
Suppose we need to find out which accounts have related contacts or no related contacts in the apex code.  Now as per the usual logic, we would fetch the data from contact object based on the AccountIds which would give us the count of accounts having related contacts. And after that, we would run another loop to iterate over the master account list and check which one does not have any related contact. Well, we can use the clone() method of Set class which would help us to save one loop. Attached is the screenshot. Note: The SOQL and list lengths are only for demonstration purpose. As per the best practice, SOQLs need to be as much as selective with proper access checks to retrieve only the intended records.

Salesforce Fact #724 | Update related records other than the latest one

Image
Suppose we have a scenario where we need to update the related records for a parent record other than the latest child record. So, we can use for each loop to iterate over the records after retrieving them in descending order of createddate. Since a collection cannot be modified while being iterated, we need to get the child records collections in a list and then remove the first record, else it would not remove the first child record from the list. Note: The code snippet is only for demonstration purpose. Attached are the screenshots.