# πŸ” Demystifying GlideRecord in ServiceNow: What, Why & How to Use It Effectively

Bhavesh Patil
Tera Contributor

Hey #ServiceNowCommunity πŸ‘‹

 

If you've ever written server-side scripts in ServiceNow, you've likely crossed paths with **GlideRecord** Glide Aggregation**β€”the backbone of database operations.

 

In this article, we'll explore:

 

βœ… What is GlideRecord & Glide Aggregation?

βœ… Why is it important?

βœ… Key methods and their uses

βœ… Step-by-step guide to writing GlideRecord scripts

βœ… Best practices for optimal scripting

βœ… Real-world use cases

 

---

## πŸ“˜ What is GlideRecord?

 

GlideRecord is a JavaScript class used to perform database operations on ServiceNow tables. It allows you to query, insert, update, or delete records directly on the server side.

 

It is commonly used in:

 

* Business Rules

* Script Includes

* Background Scripts

* Scheduled Jobs

* Script Actions

* Flow Designer (via Script step)

 

---

## πŸ“˜What is glide aggregate ?

GlideAggregate is used to get statistical data. like count the number of records in a table, to calculate the sum, min, max or average.

 

## 🧠 Why is GlideRecord  Important?

 

GlideRecord is essential for server-side scripting because:

 

* Provides direct access to ServiceNow tables (like `incident`, `task`, `cmdb_ci`, etc.)

* Enables efficient data handling using filters, sorting, and iteration

* Supports secure record manipulation with GlideRecordSecure

* Forms the foundation of custom business logic like SLAs, approvals, conditions, and notifications

 

---

## 🧰 Common GlideRecord Methods & Their Usage

 

MethodDescription
initialize()Prepares a new record before insert.
addQuery(field, value)Adds a simple condition to filter records.
addEncodedQuery()Adds complex conditions using encoded query string.
addActiveQuery()Adds a condition to return only active records (active = true).
addInactiveQuery()Adds a condition to return only inactive records (active = false).
addNullQuery(field)Filters records where a field value is null.
addNotNullQuery(field)Filters records where a field value is not null.
orderBy(field)Sorts results in ascending order based on the specified field.
orderByDesc(field)Sorts results in descending order.
chooseWindow(start, end)Retrieves a windowed subset of results (pagination).
setLimit(number)Limits the number of records returned.
query()Executes the constructed query.
next()Moves to the next record in the result set.
getRowCount()Returns the number of rows matched by the query (useful after query()).
update()Saves changes made to an existing record.
insert()Inserts a new record into the table.
deleteRecord()Deletes a single record.
deleteMultiple()Deletes all records matched by the query.
setWorkflow(false)Prevents Business Rules and workflows from triggering during update/insert.

 

## πŸ“ Steps to Write a GlideRecord Script (With Explanation)

 

Here’s how to write a basic GlideRecord script:

 

var gr = new GlideRecord('incident');         
  // Step 1: Create an object with new word, (add target table)

gr.addQuery('priority', 1);
// Step 2: Add filtering conditions

gr.orderByDesc('sys_created_on');
// Step 3: Sort the result if needed

gr.setLimit(); 
// Step 4: (Optional) Limit the result, if needed

gr.query();

// Step 5: Run the query

while (gr.next()) {
// Step 6: Loop through results

gs.info('Number: ' + gr.number);
// Step 7: Work with fields

}

 

Tip: Always test your script in the Background Script module before using it in Business Rules or Script Includes.

 

---------------------------------------------------------------------------------------------------

 

## βœ… Best Practices for Writing GlideRecord : 

 

1. use indexed fields like `sys_id`, `number`, or `active` in queries to improve performance

2. always limit result sets with `setLimit()` or specific query filters

3. avoid hardcoding table names; use variables or scoped APIs where applicable

4. use `addEncodedQuery()` for cleaner, complex query strings

5. check for results using `if (gr.next())` before accessing fields

6. use `GlideRecordSecure` when working in scoped applications to enforce security

7. log and test using `gs.info()` to understand behavior during development

 

---------------------------------------------------------------------------------------------------

 

## πŸ’‘ Real-Time Use Cases for GlideRecord

 

Here are some practical scenarios where GlideRecord is commonly used:

 

* **Auto-assign Incidents**: In a Business Rule, use GlideRecord to find the support group based on category and assign the ticket automatically.

* **Notify on Overdue Tasks**: A Scheduled Script uses GlideRecord to fetch tasks past due date and sends email reminders.

* **Mass Data Update**: Use a Background Script with GlideRecord to update thousands of records after a business rule change.

* **Check for Duplicate CI Entries**: GlideRecord can help identify and clean up duplicate entries in the CMDB.

* **Approval Escalation Logic**: GlideRecord can fetch pending approvals and reassign them if they’ve been stagnant for too long.

* **SLA Breach Alerting**: GlideRecord can be used in a Script Include to monitor SLA breaches and trigger custom notifications.


------------------------------------------------------------------------------------------------


Glide Aggregate : 

Some use cases on groupBy : 

  1. Show only the categories used in incidents and how many times each is used.

  2. Show incidents created in the last 10 days, grouped by day with count per day.

  3. Show users who raised incidents in the last 7 days and how many incidents each user raised.

  4. Show only those users who raised more than one incident.

 

------------------------------------------------------------------------------------------------

Use case : Show 'COUNT' how many incidents created in last week ?

 

var count=new GlideAggregate('incident');

count.addAggregate('COUNT');

count.query();

while(count.next()){

    gs.info(count.getAggregate('COUNT'));

}

 

---------------------------------------------------------------------------------------------------

To show SUM, MIN, MAX, AVG of any numbers field.

 

var count=new GlideAggregate('cmdb_ci');

count.addAggregate('AVG','cost');

count.setGroup(false);

count.query();

while(count.next()){

    gs.info(count.getAggregate('AVG','cost'));

}

---------------------------------------------------------------------------------------------------

 

## πŸ’‘ Pro Tip: Control System Field Updates

 

When working with GlideRecord, you may encounter cases where you want to control how system fields behave during record updates. Here are two useful methods:

 

### autoSysFields(false) :

 

Use this to prevent ServiceNow from automatically updating system fields like `sys_updated_on`, `sys_updated_by`, `sys_created_on`, and `sys_created_by`.

This is especially helpful when doing bulk updates or data migrations where you want to preserve original metadata.

 

---

 

### setForceUpdate(true) :

 

By default, ServiceNow updates a record only if a field value has changed. This method forces an update to occur even when no field values have been modified.

It’s commonly used when you want to re-trigger Business Rules, workflows, or Audit history without modifying any data.

 

---

 

Thanks for reading!

I hope this article helps you understand and use GlideRecord and GlideAggregate more effectively in your ServiceNow development journey.

Happy scripting! πŸ’»βœ¨

0 REPLIES 0