Service Now - Get Random Table Row

Thursday Jan 9, 2020

Here’s how we can get a random record from a table in Service Now.

Code

Here’s the code:

  function randomRecord(tableName) {
  		var rec = new GlideRecord(tableName);
  		rec.query();
  		if (rec.next()) {
  			var count = rec.getRowCount();
  			var randomNumber = Math.floor(Math.random() * count);
  			for (var x = 0; x < randomNumber; x++) {
  				rec.next();
  			}
  			return rec;
  		} else {
  			throw ("Table " + tableName + " is empty?");
  		}
  	},