If you are implementing business logic through Salesforce’s flow, you might need to loop through a list of records to do some manipulation. This is a very basic requirement. 

If you ever need to query records from Salesforce (let’s say all accounts where the billing country is India), it is very easy to do in SOQL and Get Records flow elements. But things will become a little tricky when the requirement says “Fetch first 5 accounts based on the created date where the billing country in India”. It is definitely very easy in SOQL with the limit statement, but in Get Records flow element, there is no way to (as of Winter’21 release) limit the record.

To overcome this situation, we can implement the counter mechanism which will basically make sure that when the # of loop iteration is greater than 5 (because we just need the first 5 accounts), the flow will not perform any business logic.

Here is the overall flow –

Here as you can see for each loop iteration, we are incrementing the counter value by 1 and then checking whether the new value is greater than 5 or not. Based on that decision element, either we are updating the account’s rating i.e. performing business logic or ignoring the business logic execution. This flow solution is definitely making sure that only for the first 5 records the business logic is getting executed.

But do you see the problem? What will happen when there are let’s say 1000 accounts satisfying the condition i.e. BillingCountry = India? In that case, the above solution will update the rating for only the first 5 accounts, but the loop will still execute for another 950 times (for the remaining 950 accounts). First of all, this 950 times loop execution is unnecessary and chances are there that it will throw limit exception.

So what is the solution?

Let me show you how to build the solution

Step 1

Copy the list of accounts fetched into a record collection variable. Include this component right next to Get Records element as shown below

Step 2

Update the loop element to make sure that it is using the newly created record collection variable, not the original collection variable generated from Get Records element. This is super important and the key to this solution.

Step 3

Store the updated accounts in a new collection variable and place it right next to the element where the account rating is getting updated. This is shown below as –

Step 4

Update the collection variable to empty when the counter value will become greater than 5. This will make sure that loop will not execute any further. 

That’s all you need to do to make sure your loop is only iterating N number of times only. I hope this solution will help you to make your loop optimized. Please provide your comments. Thank you.