Interested in a ServiceNow event built for developers? Registration for now[dev]26 is officially open!

Looking for a Complete Guide to GlideRecord and GlideAggregate Methods in ServiceNow

patilharsha
Tera Contributor

Hello Community Members,

I am learning ServiceNow scripting and want to develop a deep understanding of GlideRecord and GlideAggregate.

I am looking for reliable learning resources, documentation, or practical examples covering all important methods, including advanced methods and real-world use cases.

Specifically, I would like to learn:

  1. All important GlideRecord methods with syntax and practical examples.

  2. Query methods such as addQuery(), addEncodedQuery(), addOrCondition(), get(), and query().

  3. CRUD operations using initialize(), insert(), update(), and deleteRecord().

  4. Field methods such as getValue(), getDisplayValue(), setValue(), and getUniqueValue().

  5. GlideAggregate methods such as addAggregate(), groupBy(), getAggregate(), and addHaving().

  6. All supported aggregate types, including COUNT, SUM, AVG, MIN, and MAX.

  7. The differences between similar methods and when to use each one.

  8. Performance best practices, limitations, and common mistakes.

  9. Real-world practical tasks and interview questions using both APIs.

  10. Official documentation or a structured learning path covering beginner to advanced concepts.

I have started learning these APIs and want to understand not just the syntax but also when, why, and how to use each method effectively.

I would appreciate any official documentation, tutorials, examples, or recommendations from experienced ServiceNow developers.

Thank you for your help!

4 REPLIES 4

Ranjan Kumar2
Tera Contributor

GlideRecord

GlideRecord is a server-side ServiceNow API used to interact with records stored in ServiceNow tables. It can retrieve, create, update, and delete records from standard tables such as Incident, Problem, Change, User, and Configuration Item, as well as custom tables.

GlideRecord is commonly used in Business Rules, Script Includes, Scheduled Script Executions, Fix Scripts, and background scripts. It is primarily used when the script needs to work with individual records and access or modify their field values.

The general GlideRecord process involves creating a GlideRecord object for a table, adding one or more query conditions, executing the query, and then processing the returned records. Query conditions determine which records are retrieved, while the query execution retrieves those records from the database.

GlideRecord supports different types of queries. You can filter records based on exact values, comparison operators, text conditions, dates, reference fields, or multiple values. Multiple query conditions are generally combined using AND logic. OR conditions can also be created when the requirement is to retrieve records that meet one condition or another.

GlideRecord can retrieve one specific record or multiple records. When retrieving one record, it is best to use a unique identifier such as the record’s sys_id or a unique record number. When retrieving multiple records, the query returns a result set that can be processed one record at a time.

GlideRecord provides methods for sorting and limiting query results. Records can be sorted in ascending or descending order, and the number of returned records can be limited. Limiting results is particularly important when working with large tables because it helps reduce processing time and system resource usage.

GlideRecord can read both stored values and display values. A stored value is the value maintained in the database, such as a reference field’s sys_id. A display value is the user-friendly value shown on the form or list, such as a user’s name or an assignment group’s name.

GlideRecord can create new records by initializing a new record and setting values for the required fields. Once the field values have been provided, the record can be inserted into the table. The newly created record receives a unique sys_id.

GlideRecord can update existing records. The script first retrieves the required record, changes one or more field values, and then saves the changes. Depending on the configuration of the instance, updating a record may trigger Business Rules, flows, notifications, approvals, and audit history.

GlideRecord also supports deleting records. A single record can be deleted, or multiple records can be deleted when they match a defined query. Deletion should be performed carefully because it may be difficult or impossible to recover the affected records.

GlideRecord provides bulk operations for updating or deleting multiple records. These operations can be useful for controlled administrative activities, but they are potentially high risk. Before using them, the query should be tested independently and the expected number of affected records should be confirmed.

GlideRecord should be used carefully on large tables. Queries should be filtered as narrowly as possible, and scripts should avoid retrieving unnecessary fields or records. Using limits, indexed fields, and precise conditions can improve performance.

GlideRecord should be used when the requirement involves individual records. Typical examples include finding all active incidents assigned to a particular group, changing the state of a request, creating a new task, or updating a work note.

GlideAggregate

GlideAggregate is a server-side ServiceNow API used to perform calculations and summarize records. It is based on GlideRecord but is designed for aggregate operations rather than detailed record-by-record processing.

GlideAggregate is used when the requirement is to calculate information such as the number of records, the total of a numeric field, the average value, or the minimum and maximum values in a table.

The main advantage of GlideAggregate is that the calculation is performed at the database level. This is usually more efficient than retrieving every matching record with GlideRecord and calculating the result inside a loop.

GlideAggregate can count records. For example, it can determine how many active incidents exist, how many requests are assigned to a particular group, or how many records meet a specific date condition.

GlideAggregate can calculate the sum of a numeric field. This is useful for requirements such as calculating the total cost of approved expenses, the total planned effort for projects, or the total amount of financial transactions.

GlideAggregate can calculate averages. For example, it can be used to calculate the average resolution time, average cost, or average score across matching records. The result should be interpreted carefully because the meaning of an average depends on the selected records and the quality of the underlying data.

GlideAggregate can identify minimum and maximum values. This can help determine the earliest date, latest date, lowest amount, highest amount, shortest duration, or longest duration within a group of records.

GlideAggregate can group records by a field. For example, active incidents can be grouped by priority, category, state, assignment group, or location. The result provides a separate summary for each group instead of one overall total.

GlideAggregate can also apply conditions before calculating results. For example, it can count only active incidents, calculate the total value of approved records, or group only records created during a specified period.

GlideAggregate may return aggregate values as strings. When the result is used in additional mathematical calculations, it should be converted into an appropriate numeric type before further processing.

GlideAggregate is most useful for dashboards, reports, data validation, scheduled summaries, operational metrics, and scripts that need to make decisions based on record counts or calculated values.

Tanushree Maiti
Tera Patron

Hi @patilharsha 

 

GlideRecord

  • It is used to Read, update, insert, and delete of  individual table records. It fetches full record objects and allows you to loop through rows and manipulate field values directly .
  • Limitation: Using .getRowCount() retrieves every matching record from the database into memory before counting, which causes performance and scalability issues on large tables

 

GlideAggregate

  • It is used as an extension of GlideRecord built specifically for database-level mathematical and summary functions (COUNT, SUM, MIN, MAX, AVG).It executes direct SQL-like aggregate queries (such as SELECT COUNT(*)) at the database layer instead of loading all row data. You must call addAggregate() and retrieve results using getAggregate().
  • Limitations:
    • Cannot access or modify individual record fields.
    • Cannot perform record deletions directly; you must use GlideRecord if you need to delete records

 

 

Refer: Difference between GlideRecord() and GlideAggregate()

GlideSystem and GlideAggregate

https://www.servicenow.com/community/developer-forum/i-would-like-to-know-the-difference-between-gli...

 

https://www.youtube.com/watch?v=W8_Yc66DyL0&t=126s

 

1. For all method of GlideRecord and GlideAggregate

 https://developer.servicenow.com/dev.do#!/reference/api/australia/server_legacy/c_GlideRecordAPI#r_G...

https://developer.servicenow.com/dev.do#!/reference/api/australia/server_legacy/c_GlideAggregateAPI?...

2. 

Please Accept the solution if it assisted you with your question & Mark this response as Helpful.
Regards
Tanushree Maiti
ServiceNow Technical Architect
LinkedIn: https://www.linkedin.com/in/tanushreemaiti

Ankur Bawiskar
Tera Patron

@patilharsha 

the best way is to check on Docs about all the available and supported methods

💡 If my response helped, please mark it as correct ✅ and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 10x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

VaishnaviK3009
Kilo Sage

Hi @patilharsha ,

For learning GlideRecord and GlideAggregate, I recommend starting with the official ServiceNow documentation and then practising the methods on tables such as Incident, Problem, and User.

  • GlideRecord: Learn querying with addQuery(), addEncodedQuery(), addOrCondition(), get(), and query(), along with CRUD operations such as initialize(), insert(), update(), and deleteRecord().

  • Field methods: Practise getValue(), getDisplayValue(), setValue(), and getUniqueValue() to understand how to retrieve and update field values.

  • GlideAggregate: Use addAggregate(), groupBy(), and getAggregate() to calculate counts, sums, averages, minimums, and maximums without retrieving every matching record. Check the documentation for the supported aggregate types and addHaving() usage.

  • Performance: Avoid unnecessary queries inside loops, retrieve only the records you need, and use GlideAggregate when you need summary calculations rather than individual records.

Official documentation:

  1. GlideRecord API

  2. GlideAggregate API

For practical learning, try writing scripts to count incidents by priority, calculate the average resolution time, group incidents by state, and retrieve records based on multiple conditions. These exercises will help you understand when to use GlideRecord and when GlideAggregate is more efficient.

Always test scripts in a development instance before using them in production, especially when performing update or delete operations.

 

Example:

// GlideRecord: Retrieve active incidents
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.query();

while (gr.next()) {
    gs.info(gr.getValue('number'));
}

// GlideAggregate: Count active incidents
var ga = new GlideAggregate('incident');
ga.addQuery('active', true);
ga.addAggregate('COUNT');
ga.query();

if (ga.next()) {
    gs.info('Active incident count: ' +
        ga.getAggregate('COUNT'));
}

Mark this as Helpful if it clarifies the issue.
Accept the solution if this answers your question.

Regards,
Vaishnavi
Technical Consultant