How to randomly pull 25 records from a table?

e_wilber
Tera Guru

I'm working on a flow that sets the Description field on the RITM record where I need to pull 25 random assets from alm_asset (the display name).


I know how to query the table and get results, but how do I randomly pull in 25 records so I can built a list?

7 REPLIES 7

TheCung
Tera Contributor
SELECT RecordID  FROM your_table_name ORDER BY RAND() LIMIT 25;

Hope it helps

How would you build that into a glidequery? 


I know we have a limit option as well as an OrderBy, but I don't see how to apply this rand() you mentioned

TheCung
Tera Contributor

Then hope this helps!

var gr = new GlideRecord('your_table_name'); // Replace with your actual table
gr.orderBy('record_id'); // Orders the records (record_id is unique, but you can use other fields)
gr.query();

var records = [];
while (gr.next()) {
    records.push(gr.record_id);
}

// Shuffle the records randomly
records = records.sort(() => 0.5 - Math.random());

// Select 25 random records
var randomRecords = records.slice(0, 25);
gs.info('Random Records: ' + randomRecords);

AshishKM
Kilo Patron
Kilo Patron

Hi @e_wilber , 

Are you trying using GlideRecord call on Asset [ alm_asset ] table, if yes then you can apply setLimit(25) for 25 records only.  For random number you need to add some random number logic and get the records.

 

var numRecs = gr.getRowCount(); // Get the total number of records found
var randomNumber = Math.floor(Math.random() * numRecs); // Generate a random number between 0 and (numRecs - 1)

 

Sample Code

// Get a random record from a GlideRecord query
var gr = new GlideRecord('table_name'); // Replace 'table_name' with the actual table
gr.addQuery('field', 'value'); // Add your query conditions
gr.query();

if (gr.hasNext()) {
  var numRecs = gr.getRowCount(); // Get the total number of records found
  var randomNumber = Math.floor(Math.random() * numRecs); // Generate a random number between 0 and (numRecs - 1)
  if(numRecs > 0) {
      gr.setRow(randomNumber); // Set the record to the random row
      var randomRecord = gr; // Access the random record
      // ... do something with the randomRecord ...
  } else {
      // Handle the case where no records were found
      // For example, log a message or return a default value
      gs.log("No records found for the query");
      var randomRecord = null; // Or return null or a default object
  }
} else {
  // Handle the case where no records were found
  // For example, log a message or return a default value
  gs.log("No records found for the query");
  var randomRecord = null; // Or return null or a default object
}

 

-Thanks,

Ashish Mishra

 


Please mark this response as correct and helpful if it helps you can mark more that one reply as accepted solution