Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Scripting

Server-Side Scripting and GlideRecord in ServiceNow

Learn server-side scripting in ServiceNow with GlideRecord: query tables, filter with addQuery, insert, update and delete records, and use GlideAggregate for counts.

Flows and forms cover most needs without code. When they do not, you write server-side JavaScript that runs on the instance. Almost every server script starts with one class: GlideRecord, which reads and writes table rows. If you learn it well, business rules, script includes and scheduled jobs all become easy.

ServiceNow scripts run on the instance, not in this page. The GlideRecord examples below are read-only code you can paste into System Definition > Scripts - Background on your own developer instance. The runnable blocks are labelled stand-ins: a small JavaScript class that imitates GlideRecord so you can practice the pattern. Do not run background scripts on a production instance.

Where server scripts run

Server-side code lives in business rules, script includes, scheduled script executions, UI actions, flow script steps, Scripted REST APIs and more. The engine is JavaScript (ES5 syntax with growing support for newer syntax in current releases; check your release's documentation). You cannot use browser objects like document or window on the server.

To experiment, open System Definition > Scripts - Background, type code and press Run script. Output from gs.info() appears in the results. Use a development instance only.

Query pattern

JavaScript
var gr = new GlideRecord('incident');   // 1. table name
gr.addQuery('active', true);            // 2. filters
gr.addQuery('priority', 1);
gr.orderByDesc('sys_created_on');
gr.setLimit(10);
gr.query();                             // 3. run it
while (gr.next()) {                     // 4. loop over rows
  gs.info(gr.number + ': ' + gr.short_description);
}

The four steps are always the same: create, filter, query(), loop with next(). Inside the loop, gr points at the current row, and gr.fieldname reads the value. Use gr.getValue('field') for the raw string and gr.getDisplayValue('field') for a reference's display name.

Useful filters:

Method Meaning
addQuery('field', value) Field equals value
addQuery('field', '>', 5) With an operator
addActiveQuery() Active is true
addEncodedQuery('active=true^priority=1') Copy the encoded query from a list filter
addNullQuery('field') Field is empty
orderBy, orderByDesc Sorting
setLimit(n) At most n rows

A tip: build a filter in a list, right-click the breadcrumb and choose Copy query, and paste it into addEncodedQuery. It is the easiest route to a correct query.

Get one record

JavaScript
var gr = new GlideRecord('incident');
if (gr.get('number', 'INC0010001')) {   // get(field, value) or get(sys_id)
  gs.info(gr.short_description);
}

get() returns true or false, and loads the first match.

Insert, update, delete

JavaScript
// insert
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description = 'Printer on floor 3 is jammed';
inc.priority = 3;
var newId = inc.insert();               // returns sys_id

// update one
var gr = new GlideRecord('incident');
if (gr.get(newId)) {
  gr.state = 2;                         // In Progress
  gr.update();
}

// delete
if (gr.get(newId)) { gr.deleteRecord(); }

For many rows, updateMultiple() and deleteMultiple() run set-based and are faster, but they skip some per-row logic (for example, updateMultiple does not run business rules unless you handle it). Read the docs for your release before using them on important data.

An update() or deleteRecord() inside a loop runs business rules and may fire notifications for every row. Test on a few records first and be careful with gs.setWorkflow(false): it suppresses rules and should be a deliberate choice.

GlideAggregate for counts

Looping through rows to count them is slow. GlideAggregate asks the database:

JavaScript
var ga = new GlideAggregate('incident');
ga.addQuery('active', true);
ga.addAggregate('COUNT', 'priority');
ga.groupBy('priority');
ga.query();
while (ga.next()) {
  gs.info('P' + ga.priority + ': ' + ga.getAggregate('COUNT', 'priority'));
}

Dot-walking

References are followed with dots: gr.caller_id.manager.email returns the manager's email. Each dot is another database read, and a null reference returns empty, not an error. Still, prefer an explicit check for clarity.

Logging

Use gs.info, gs.warn, gs.error and gs.debug. Output goes to the System Log (table syslog). Never log passwords or personal data.

A GlideRecord stand-in

The class below is invented for this lesson. It keeps rows in memory and offers the same fluent steps: addQuery, orderBy, setLimit, query, next. It lets you practice the loop shape without an instance.

JS Stand-in: a mini GlideRecord over in-memory tables

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that gr.number changes each time next() runs: gr is one object that points at the current row. A frequent beginner bug is saving gr into an array and expecting it to hold separate rows. Copy the values you need instead, as the next stand-in shows.

JS Stand-in: copy values, not the cursor

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Habits that matter

  1. Always filter. An unfiltered query on a large table can be slow and expensive.
  2. Avoid queries in loops over other queries when a single joined or encoded query works.
  3. Use setLimit while testing.
  4. Check results: get() and next() return booleans for a reason.
  5. Use GlideAggregate for counts and sums.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the usual order of steps in a GlideRecord query?

    Create the object, add filters, run query(), then step through rows with next().
  2. 2. What does gr.get(sys_id) return?

    get() loads the first match and returns a boolean.
  3. 3. Which API is better for counting open incidents per priority?

    GlideAggregate lets the database compute counts and groups.
  4. 4. Why is it risky to call update() on thousands of rows in a loop?

    Each update triggers the normal automation, so test small and be deliberate.

Summary

  • Server scripts use GlideRecord: create, filter, query(), loop with next().
  • Use get() for one record, insert/update/deleteRecord for changes and GlideAggregate for counts.
  • gr is a cursor; copy values you need, and always filter and limit queries.
  • Run background scripts only on development instances.

Next: Business Rules