ServiceNow GlideRecord Code Generator

Live

Pick a table, an action and where it runs. Get GlideRecord and GlideQuery code to read, count, create, update or delete records, checked and ready to paste.

Start from an example

1 Where it runs

Script
Application

2 What to do

3 Which records

4 Fields to read

numbershort_descriptioncaller_idstate

5 Options

Reads Number, Short description, Caller and State of incident records where Active is true and Priority is 1 - Critical, sorted by Created (descending), at most 100.

Background script global

Script Checker: no problems
Scripts - Background
var gr = new GlideRecord('incident');
gr.addEncodedQuery('active=true^priority=1^ORDERBYDESCsys_created_on');
gr.setLimit(100);
gr.query();
while (gr.next()) {
    var number = gr.getValue('number');
    var shortDescription = gr.getValue('short_description');
    var caller = gr.getDisplayValue('caller_id');
    var state = gr.getDisplayValue('state');
    gs.info(number + ' | ' + shortDescription + ' | ' + caller + ' | ' + state);
}

Where to put it

Run it

  • System Definition › Scripts - Background, on a sub-production instance first.
  • Leave the scope on global.
  • To move the change with an update set, save it as a Fix Script instead (System Definition › Fix Scripts).

Good to know

  • References and choices are read as the text users see. Switch off display values to get sys_ids and stored values.
Open the Script Checker

Which call for which job

Read records
addEncodedQuery() or addQuery(), query(), then while (gr.next())
One record
gr.get(sys_id), or gr.get(field, value)
Any at all?
setLimit(1), query(), hasNext()
How many
GlideAggregate with addAggregate('COUNT')
Create
initialize(), setValue(), insert()
Change
setValue() and update(), or updateMultiple()
Delete
deleteRecord(), or deleteMultiple()

Need every method? The GlideRecord cheat sheet lists them with examples.

Mistakes the generated code avoids

getRowCount() to count
Reads every matching row. GlideAggregate counts in the database.
No setLimit(1) to check existence
The query keeps reading after the first match.
gr.field without getValue()
Stores a GlideElement that changes as the loop moves on.
current.update() in a business rule
Saves the record again and runs every rule twice.
insert() without initialize()
The new record misses its default values.
A query inside a loop
One database call per record. Query once, or use GlideAggregate.
deleteMultiple() without a filter
Empties the table.

Where the code runs changes what it can do

  • Background and fix scripts run once, as you. Use them for data fixes: the generator adds a dry run and a limit per run, and logs what it did.
  • Business rules run on every save of their table and get current (and previous, except in async rules). The generator links records to current, skips the record being saved when it looks for duplicates, and only logs errors.
  • Script includes are called by other code. The method takes the value to match as a parameter, uses addQuery() so the value cannot add its own conditions, and returns plain objects, a number or a sys_id instead of logging.

GlideRecord or GlideQuery?

Both reach the same database. GlideQuery fails loudly on a misspelt field, where GlideRecord quietly ignores the condition and matches every record, and it returns numbers and booleans rather than strings. GlideRecord is available everywhere, takes encoded queries as they are, and has setDisplayValue(), dot-walking and the other conveniences most scripts use. Pick either tab above; when GlideQuery cannot do the job (counting per group, display values, dot-walked fields), the generator says so.

Frequently asked questions

How do I query records with GlideRecord?

Create the object for the table, add conditions, call query() and loop with next(): var gr = new GlideRecord('incident'); gr.addEncodedQuery('active=true^priority=1'); gr.query(); while (gr.next()) { gs.info(gr.getValue('number')); }. Copy the encoded query from a list filter (right-click the breadcrumb › Copy query) so the conditions match what you saw in the list.

What is the difference between getValue() and getDisplayValue()?

getValue('caller_id') returns what is stored: the sys_id of a reference, the value of a choice (6) and dates in UTC. getDisplayValue('caller_id') returns what users see: the name, the choice label (Resolved) and dates in the user’s time zone. Both return strings. Use values for logic and comparisons, and display values for messages.

How do I count records in ServiceNow?

Use GlideAggregate: addAggregate('COUNT'), query(), then getAggregate('COUNT'). The database does the counting, and groupBy() gives one count per value. getRowCount() on a GlideRecord reads every matching row first, which is slow on big tables.

How do I update many records at once?

Either loop and call update() on each record, or set the values with setValue() and call updateMultiple(). updateMultiple() is one database call and much faster. The loop can list what it changes, count it, stop after a number of records and use setDisplayValue(), which makes it the safer choice for a first run of a data fix.

What does setWorkflow(false) do?

It stops business rules, and with them the notifications, flows, workflows and audit history they would trigger, for the changes made through that GlideRecord. It is for data fixes that should not look like user activity. Leave a comment saying why, because the next person will wonder why nothing reacted. autoSysFields(false) is the companion that keeps Updated and Updated by as they were.

What is GlideRecordSecure?

GlideRecordSecure works like GlideRecord but applies the ACLs of the user the code runs as: records and fields they may not read are left out, and changes they may not make fail. Use it in code that answers users, such as script includes called from GlideAjax, REST APIs and portal widgets. Plain GlideRecord ignores ACLs, which suits system jobs.

Should I use GlideQuery or GlideRecord?

GlideQuery (Paris and later) is a newer API on top of GlideRecord: it throws an error for a field name it does not know instead of ignoring the condition, returns JavaScript types, and reads like a chain. GlideRecord is everywhere, is what most examples use, and supports encoded queries directly. The generator writes both where GlideQuery can do the job; in scoped apps it is called as global.GlideQuery.

How do I run a data fix safely?

Try it on a sub-production instance first. Start with a dry run that only lists the records it would change, limit each run with setLimit() so a mistake stays small, and save the script as a Fix Script if the change must move with an update set. For deletes, check that no reference to those records has a cascade rule that deletes more than you expect.

Why should a business rule not call current.update()?

In a before rule, changes to current are saved anyway when the rule finishes. In an after rule, current.update() saves the record a second time, so every business rule runs again and can loop. Change current in a before rule, and use after or async rules to change other records, which is what the generator does.