Get a Single Record in ServiceNow, now with multiple!

In ServiceNow there are multiple different ways to get records. Below we will highlight some of the basic and more advanced versions that you can use to help you achieve your goals!

Get a single record

To get a single record in ServiceNow, we first start by initializing a new GlideRecord for the table that you wish to search from.

var record = new GlideRecord('incident');

Next, we run the get command, this command pulls a single matching record (usually the first, depending on sort order) from the Database. The default value passed to the get command is a sys_id , however you can change the field you want to query by adding an additional variable to the call, 2 examples below.

// Default usage
var recordExists = record.get('ca7eee260fc845a9b853f209127d3b7d');

// Specify field name
var recordExists = record.get('short_description','My Incidents short description');

Once you have determined if a record exists or not (recordExists value will be null if no record is returned), then you can access the record using the recordExists variable, see below.

if(recordExists){
  gs.info("My record Number: "+ recordExists.getDisplayValue('number'));
}

Putting it all together, you can even short hand the recordExists check, remove the variable and simply check the outcome of the if statement.

var record = new GlideRecord('table_name');
if(record.get('sys_id')){
  gs.info("My record Number: "+ recordExists.getDisplayValue('number'));
}

if statement returns true/false depending on if the record exists

Get Multiple Records and itterate the results

To get multiple records it is much the same, however we perform a query function and then itterate over the returned values with a while loop, see below.

You'll note that I've used an example of a standard addQuery and also a more advanced addEncodedQuery. AddQuery is very useful for matching against a single field. AddEncodedQuery is very useful if you have a more complex query, or if you've copied a query string from a list filter.

// initiate our Glide Record on the Incident table
var records = new GlideRecord('incident');

// Add our queries to filter the results
records.addQuery("active","true");
records.addEncodedQuery("priority=4^category=software");

// perform the query
records.query();

// Itterate on results
while(records.next()){
  // Each loop of this while loop, records variable will have the next row of the itteration
  gs.info("Current record: "+records.getDisplayValue("number");
}