OBLYTECH Logo
OBLYTECH Logo

GlideRecord API in ServiceNow: Method Reference for Queries

GlideRecord API in ServiceNow: Method Reference for Server-Side Queries and Updates

GlideRecord is the server-side class for reading, creating, changing and deleting rows in one table at a time from a script. You build a query with addQuery, addEncodedQuery or get, run it with query, step through rows with next, then write with insert, update, updateMultiple or deleteRecord. It does not apply access controls on its own.

This page is a method-level reference. For the concept of what a GlideRecord object is and how it maps to a table row, read GlideRecord explained. Here the focus is on which method to call, what it returns, and where it bites.

The lifecycle of a GlideRecord script

A GlideRecord script runs in four steps: construct, filter, execute, iterate. The constructor takes a table name, so new GlideRecord('incident') gives you an object bound to the incident table. Nothing has touched the database at that point.

Filtering methods add conditions to that object. Execution happens when you call query(). After that, the object sits just before the first result, and each call to next() moves to the following record and returns true while a record exists. That is why next() is the condition of a while loop.

var gr = new GlideRecord('incident');
gr.addActiveQuery();
gr.addQuery('priority', 1);
gr.orderBy('short_description');
gr.setLimit(10);
gr.query();
while (gr.next()) {
    gs.info(gr.getValue('number') + ' ' + gr.getDisplayValue('state'));
}

Building the query

addQuery and its two forms

addQuery accepts two shapes, and an encoded query string belongs in addEncodedQuery. With two arguments, a field name and a value, it adds an equality filter, and the value match is case-insensitive. With three arguments, a field, an operator and a value, it supports numeric comparisons and string operators such as IN, STARTSWITH and CONTAINS.

var kb = new GlideRecord('kb_feedback');
kb.addQuery('comments', 'CONTAINS', 'Excel');
kb._query();

addEncodedQuery

addEncodedQuery(query, enforceFieldACL) adds an encoded query string to the conditions already on the object. The second parameter is optional, defaults to false, and passing true enforces field ACLs. By default, an invalid field name is dropped from the condition, so the query can return far more rows than written. Check a string with isValidEncodedQuery(query) before use, and test any script that updates or deletes on a sub-production instance first. The full set of traps is covered in the encoded query guide.

Null checks, active records and joins

  • addNullQuery(fieldName) keeps records where the field is null; addNotNullQuery(fieldName) keeps the opposite.
  • addJoinQuery(joinTable, primaryField, joinTableField) adds a subquery based on a related table. Both the primary field and the join field default to sys_id, so you name a field when the relationship uses another key. It is a subquery, not a true join, so you cannot read values from the related table in the results, and base-table fields are the ones accessible.

Ordering, limiting and windows

orderBy(name) sorts ascending and orderByDesc(name) sorts descending. Call either one repeatedly to sort by several columns in sequence.

setLimit(maxNumRecords) caps how many records are fetched. chooseWindow(firstRow, lastRow, forceCount) limits results to a row range, where firstRow is zero-based and inclusive and lastRow is exclusive. It triggers a COUNT(*) query.

The order of these two calls changes the result. If chooseWindow() is called first, a later setLimit() overwrites its window. If setLimit() is called first, the window takes effect and overrides the limit.

Fetching a single record with get

get() loads one matching record and returns a Boolean. With one parameter, the value is treated as a sys_id, and if nothing matches, as a display value. With two parameters, the first is a field name and the second is the value to match.

var inc = new GlideRecord('incident');
if (inc.get('caller_id.name', 'Sylivia Wayland')) {
    gs.info(inc.getUniqueValue());
}

Reading field values safely

Several methods read values, and they behave differently.

Method Returns Notes
getValue(name) String or null Booleans come back as “0” or “1”.
getDisplayValue() String Depends on field type: choices, dates, encrypted fields and references each display differently.
getElement(fieldName) GlideElement The full field object; equivalent to dot-walking.
getUniqueValue() String or null The primary key, usually the sys_id.

Prefer getValue() or getDisplayValue() over dot-walking. Dot-walking retrieves whole objects, which uses more storage and can cause trouble in arrays or Service Portal. If you must dot-walk, finish with toString(), as in the example below.

var managers = [];
var gr = new GlideRecord('incident');
gr.query();
while (gr.next()) {
    managers.push(gr.caller_id.manager.name.toString());
}

Creating records

To create a row, call initialize() to start an empty record, set values, then call insert(). insert() returns the new sys_id, or null if the insert fails.

var gr = new GlideRecord('incident');
gr.initialize();
gr.setValue('short_description', 'Printer offline on floor 3');
var newId = gr.insert();

setValue(name, value) sets a field value, and the value must match the field’s data type. setValue() passes password2 data as clear text, which results in an error about expecting encrypted data.

Updating one record or many

update

update() saves pending changes. If the record does not already exist, it is inserted.

var inc = new GlideRecord('incident');
if (inc.get(sysId)) {
    inc.setValue('short_description', 'Updated from script');
    inc.update();
}

updateMultiple

updateMultiple() applies the changes you set to every record the query returns, without a next() loop.

var gr = new GlideRecord('incident');
gr.addActiveQuery();
gr.setValue('state', 4);
gr.updateMultiple();

addValue for counters

addValue(field, value) adds or subtracts at the database level during an update or insert. The field must be a number field. If you call setValue() on the same field first, the addValue() call is skipped and an error is logged.

Deleting records

deleteRecord() deletes the current record and returns false if no record was found. deleteMultiple() deletes all records matching the query and does not delete attachments. setLimit() does not limit what deleteMultiple() removes. Do not use deleteMultiple() on tables with currency fields, or combine it with chooseWindow() on large tables. The glide.db.forced.chunk.threshold system property sets the point above which deletions and updates are forced into chunks, which helps prevent replication problems on huge tables. Read the query back with getEncodedQuery() before running a delete. For a different approach to set-based updates and deletes, see the GlideQuery guide.

Controlling business rules and aborting actions

setWorkflow(enable) turns business rules, script engines and audits on or off for the operation. Call setWorkflow(false) when you intend to skip them.

Inside a business rule, setAbortAction(true) aborts the next insert, update or delete, though other business rules still run. isActionAborted() reports whether the current database action is set to abort. operation() returns “insert”, “update” or “delete”, so one business rule can branch for all three.

Counting rows and the cost of COUNT

getRowCount() returns the number of rows returned, and next() has to be called first. chooseWindow() used with query() triggers a COUNT(*) query, and getRowCount() is not as efficient as GlideAggregate. When you need a count and not the records, use GlideAggregate.

Access control: GlideRecord versus GlideRecordSecure

GlideRecord does not enforce ACLs automatically. For the rules themselves, see the access control list guide. To check access you call canRead(), canWrite(), canDelete() and canCreate() yourself. canRead() reflects all ACL types: roles, scripted and conditional.

var gr = new GlideRecord('incident');
gr.query();
var visible = [];
while (gr.next()) {
    if (!gr.canRead()) continue;
    visible.push(gr.getUniqueValue());
}

GlideRecordSecure is a version of GlideRecord that enforces ACLs, so the loop above works without the canRead() check. It is used the same way as GlideRecord and enforces access controls, so it suits sensitive data. GlideRecord suits data that does not need access controls enforced.

Names that collide with method names

next() fails on a table that has a field named “next”, and query() can cause errors on a table with a field named “query”. The underscore variants _next() and _query() do the same job and are meant for those tables.

Frequently asked questions

Does GlideRecord check ACLs when it queries a table?

No. It leaves access checks to you through canRead, canWrite, canDelete and canCreate. GlideRecordSecure enforces ACLs automatically.

How do I update many records without a loop?

Set the values with setValue and call updateMultiple on a query that matches the target rows.

Why did my query return far more records than expected?

By default, an encoded query with an invalid field name has that part dropped, so the filter is wider than written. Validate with isValidEncodedQuery, and test on a sub-production instance before running any write or delete.

What is the difference between get and a query loop?

Get loads one matching record and returns true or false. A query loop returns every matching record, which you step through with next().

Which method should I use to count records?

GlideAggregate is the more efficient route when you need a count and not the records. getRowCount is not as efficient as GlideAggregate.