Flow Bits – Keeping your DML Outside of the Loop
DML
Today we are addressing the importance of keeping Database Manipulation Language (DML) operations outside of your loops within a flow. DML refers to anytime your flow directly interacts with your Salesforce data. Each of these operations is represented by its own element in Flow Builder. Each of these operations can be performed on one or many records at once. The limit for DML operations within a single flow is 100.
Loops
Loops in a flow are created in two different ways. First is the Loop element.
The loop element takes each item within a collection and passes it individually through the operations set up inside the loop. Once all records have been passed through the loop it continues with any additional steps ‘After last item’.
Another way to create a loop is with a Decision element. In the example below, as long as the NumberOfPayments variable is greater than 0 the flow will keep creating new records and adding them to a collection.
As the record gets added to the collection we use the same assignment record to reduce the NumberOfPayments variable by 1. Eventually, the loop will end once that variable is reduced down to 0.
The 100 Query Limit
In each of the example loops above, every collection item undergoes every operation inside that loop. If one or more of the DML elements is placed within the loop every item in that collection will trigger a DML transaction and count against the 100 query limit. In the examples below the two loops are identical except the loop on the left updates each record as it passes through the loop while the loop on the right adds each updated record to a collection and then executes a mass update of the entire collection in one DML execution.
For comparison, the loop on the left could never pass more than 100 records through it. The loop on the right could pass 1000s of records as the only limit here would be the total limit for transactions within a flow being 20,000.
Next time you are building a flow, keep an eye on where you are placing your DML operations and avoid putting these elements within a loop. This will keep your flows much more efficient and drastically increase the number of records the flow is able to process at once.
Look for more Flow Bits in upcoming blog posts. How are you using flows? Please feel free to comment directly at me in the Salesforce Trailblazer Community or on Twitter @jpbujold.