Counting Records in a Collection in Salesforce Flow

Counting Records in a Collection in Salesforce Flow

Many folks may have to get counts of records in Salesforce. Lucky for us, Salesforce Flow makes it easy to count records. Effectively, if what we are looking to count is in a Collection Variable, we can count it simply using an Assignment element and a new variable of type Number. See the following example, where we want to see how many accounts exist that fit certain criteria.

In the first element, we get the Accounts we want to count up. In the following element, we use the Equals Count operator to retrieve the count from the collection.

Then, we can use acctCount in a display element or in an update element to assign to a record.

What if we wanted to do something more involved, such as stamp the number of Contacts each Account has on the Account record? The complexity jumps slightly, but it is still something Flow allows us to do easily! We will write this with collection filters to avoid extra loops.

👩‍💻
For those who also deal with Apex code, using a collection filter is a really great way to avoid what are essentially nested for loops, just in Flow. If I have 200 objects to loop in loop 1, and 200 objects in the sub-loop, I have 40000 total loops to run. If I use a collection filter, I only have to run the primary 200 loops and search within my collection.

Here is one way to do this in a single flow.

Overview of the Flow

The steps you'd want to take

  1. Get all the accounts you want to count the Contacts for (Get Records)
  2. Loop over the Accounts (Loop)
  3. Assign the Account Ids to a collection variable of type Text (Assignment)
  4. Get all contacts where AccountId IN yourAccountIdCollectionVariable (Get Records)
  5. Loop your original Account collection (Loop)
  6. Filter your Contacts collection where AccountId equals your current Looped Account's Id (Collection Filter)
  7. Assign your current loop's Account field that will take the Contact count with the Equals count operator on the Filtered Collection, assign your Account to a new collection to be updated (Assignment)
  8. Update your new Account collection (Update records)

This structure should word whenever you have to count a child object and add the count to the parent object in bulk at a click of a button. However, this process can take longer where you have thousands of Accounts, each with hundreds of Contacts. In those sorts of situations, you might want to consider using a scheduled Flow (the format will be far simpler).

In situations where you want this to happen in real time, you could consider running in a record triggered context off of insertions or deletions of Contact records. In this case, you would also need a process to backfill existing Contact counts (and you could use either the Scheduled structure or Screen structure to complete that).