0

Scenario: Each day Salesforce users create x number of new opportunities. At the end of the day, I would like to create a function (Workflow/APEX trigger etc.) to randomly select 3 of opportunities that were created in that day to send a survey to.

Conceptually i feel like this is possible, but I have never done something like this so I am not sure if it is.

SlowBlurry
  • 171
  • 2
  • 12

1 Answers1

1

First get a count of the records created that day.

Integer size = Database.getCountQuery('select count() from Opportunity where CreatedDate = TODAY');

Then use OFFSET to get your random record.

Integer offset = Math.floor(Math.random() * size).intValue();
Opportunity randomOppty = [select Id from Opportunity where CreatedDate = TODAY LIMIT 1 OFFSET :offset];

You'll have to randomize offset for each SOQL call.

ScottW
  • 421
  • 2
  • 7