Back to LinkedIn posts

LinkedIn post 318

How would you get a random sample of N records in Salesforce?

How would you get a random sample of N records in Salesforce?

You don't have Marketing Cloud so you cannot use SELECT TOP N ... ORDER BY newid() or use random Data Extensions.

Some examples of when you might need a random sample:
* need to send a survey to a random sample of contacts
* extract a random sample of cases to send for evaluation
* raffle a coupon code to a random selection of past customers
* run a pilot campaign with a random group
* if you had a similar requirement, please tell me in the comments below πŸ‘‡πŸΌπŸ’¬

Here are a few ideas:
1) Extract and do the random selection outside Salesforce - that can be prohibitive if you have thousands of records.

2) Use one of the date-based formulas explained in this article "How to get a lead assigned to a random person in Salesforce"
πŸ”— https://www.linkedin.com/pulse/how-get-lead-assigned-random-person-salesforce-draft-fernando/

3) Repeat the query SELECT Id FROM Contact LIMIT 1 OFFSET :randomNumber in Apex (the randomNumber has to be below 2000) until you get N records (BAD: query in a loop!)

4) Create an object with a number field and a lookup (or master-detail relation), then use Apex Trigger to get a random number (external id) and associate it with new/existing records. Then query SELECT Parend_Id__c FROM Random__c WHERE RandomNumber__c >= :lowerRandomNbr AND RandomNumber__c <= :upperRandomNbr LIMIT :qtyRecordsToSample

5) any other ideas? Please share them below. πŸ‘‡πŸΌπŸ’¬

How would you get a random sample of N records in Salesforce?