Return N Random Records
Created By: Derek Camp, RafterOne
Eric Smith did a good job explaining and writing the “Return First N Records” action. But it didn’t quite meet my use-case, nor did anything else in the Collection Actions library. So here is “Return N Random Records”!
Input a record collection (using any type of object) with a record count, and the action will output a record collection randomly selected from the input as well as a count of how many records were returned.

My need was for Lead Assignment to Contractors. I build a collection of Accounts that meet the assignment criteria and I want to share this lead with five of them. Round robin assignment was too complicated for this requirement; we wanted to leverage the assignment criteria on the accounts to control who was eligible and then randomly select who gets the lead.
Flow has no built-in random number generator, so we’ll need an invocable method just to get that. There are already some options out there. But then once I have a random number N, I struggled to figure out an efficient way to pull the Nth record out of a collection. None of the built-in flow collection actions seemed to cover it – remove first, remove position, these all added or removed values, but I needed to get and use the value. None of the other Collection Actions hit my specific need either. I thought I’d have to do excessive looping to go through the collection again and again to get my random records. This landed me back at the invocable method to handle the collection processing easier than flow itself.

If you request more random records than are available in the collection, it will return the whole collection. It does make sure to not randomly select the same record twice.
Attributes
| Attribute | Type | Notes |
| INPUT | ||
| Input Record Collection | sObject Collection | Collection of Records |
| Record Count | Integer | Number of records to randomly select from input |
| OUTPUT | ||
| Output Record Collection | sObject Collection | Collection of Records |
| Return Count | Integer | Number of records returned |
Installation
This component is installed with the Collection Actions package version 3.2.0 or later.
Release Notes
3/18/2024 – Eric Smith – v1.0.1
Fixed intermittant test class error (index out of bounds)
Available in Collection Actions package version 3.2.2 or later
9/5/2023 – Derek Camp – v1.0
