GlideRecord API
GlideRecord is one of the most fundamental and widely used APIs in ServiceNow development. It provides a powerful interface for performing database operations on ServiceNow tables, enabling developers to query, insert, update, and delete records programmatically through server-side JavaScript. At … GlideRecord is one of the most fundamental and widely used APIs in ServiceNow development. It provides a powerful interface for performing database operations on ServiceNow tables, enabling developers to query, insert, update, and delete records programmatically through server-side JavaScript. At its core, GlideRecord acts as an object-oriented representation of a database table record. When you instantiate a GlideRecord object, you specify the table name, and then you can build queries and interact with records in that table. **Key Operations:** 1. **Querying Records:** Using methods like `addQuery()`, `addEncodedQuery()`, and `query()`, developers can retrieve specific records based on conditions. The `next()` method iterates through the result set, similar to a database cursor. 2. **Inserting Records:** The `initialize()` method prepares a new record, after which field values can be set using `setValue()`, and `insert()` commits the new record to the database. 3. **Updating Records:** After querying existing records, developers can modify field values and call `update()` to save changes. For bulk updates, `updateMultiple()` efficiently updates all matching records. 4. **Deleting Records:** The `deleteRecord()` method removes individual records, while `deleteMultiple()` removes all records matching a query. **Common Methods:** - `addQuery(field, operator, value)` – Adds a filter condition - `get(sys_id)` – Retrieves a single record by sys_id - `getRowCount()` – Returns the number of matching records - `hasNext()` – Checks if more records exist in the result set - `setLimit(n)` – Restricts the number of returned records - `orderBy()` / `orderByDesc()` – Sorts results **Best Practices:** Developers should always use `setValue()` instead of direct dot-notation assignment for setting values, apply proper query filters to avoid performance issues, and use `setLimit()` when only a subset of records is needed. GlideRecord respects ACLs in scoped applications, ensuring security compliance. For the Certified Application Developer exam, understanding GlideRecord is essential as it underpins Business Rules, Script Includes, Scheduled Jobs, and virtually all server-side scripting in ServiceNow.
GlideRecord API – ServiceNow CAD Exam Guide
Why Is the GlideRecord API Important?
The GlideRecord API is the single most important server-side scripting tool in ServiceNow. It is the primary mechanism through which developers interact with the database—creating, reading, updating, and deleting (CRUD) records in any table. Virtually every server-side script, whether it is a Business Rule, Script Include, Scheduled Job, or Fix Script, relies on GlideRecord to query and manipulate data. For the ServiceNow Certified Application Developer (CAD) exam, a solid understanding of GlideRecord is non-negotiable. Questions about it appear frequently and test both conceptual knowledge and practical coding ability.
What Is the GlideRecord API?
GlideRecord is a server-side JavaScript API that provides an object-oriented way to interact with ServiceNow database tables. When you instantiate a GlideRecord object, you pass in the name of the table you want to work with. You then build a query, execute it, and iterate through the results. Think of each GlideRecord object as a pointer that moves row by row through a result set, much like a database cursor.
Key characteristics:
- Server-side only (there is a separate GlideRecord available client-side via GlideAjax, but the CAD exam focuses primarily on server-side usage).
- Works on any table in the ServiceNow platform, including custom tables.
- Respects Access Control Rules (ACLs) unless explicitly run in a context that bypasses them (e.g., running as system).
- Returns GlideElement objects for each field, not raw primitive values.
How Does the GlideRecord API Work?
Below is a walkthrough of the core operations:
1. Querying Records (Read)
To query records from a table, you follow this pattern:
var gr = new GlideRecord('incident');
gr.addQuery('priority', 1);
gr.query();
while (gr.next()) {
gs.info(gr.number + ' - ' + gr.short_description);
}
Step-by-step:
- new GlideRecord('incident') – Creates a GlideRecord object targeting the incident table.
- addQuery('priority', 1) – Adds a filter condition (WHERE priority = 1).
- query() – Executes the query against the database.
- next() – Moves the pointer to the next record in the result set. Returns true if a record exists, false when the result set is exhausted.
- gr.number – Accesses the value of the 'number' field on the current record (actually returns a GlideElement object; use gr.getValue('number') for the string value).
2. Retrieving a Single Record
var gr = new GlideRecord('incident');
if (gr.get('sys_id_value_here')) {
gs.info(gr.short_description);
}
The get() method retrieves a single record by sys_id (or by a field name/value pair). It returns true if a record is found. This is a shortcut that combines addQuery, query, and next into one call.
3. Inserting Records (Create)
var gr = new GlideRecord('incident');
gr.initialize();
gr.short_description = 'New incident from script';
gr.priority = 2;
gr.insert();
- initialize() – Prepares a new empty record with default values.
- insert() – Saves the new record to the database and returns the sys_id of the newly created record.
4. Updating Records (Update)
var gr = new GlideRecord('incident');
gr.addQuery('priority', 1);
gr.query();
while (gr.next()) {
gr.priority = 2;
gr.update();
}
- update() – Saves the changes to the current record. Note: This fires Business Rules by default.
5. Deleting Records (Delete)
var gr = new GlideRecord('incident');
gr.addQuery('active', false);
gr.query();
while (gr.next()) {
gr.deleteRecord();
}
- deleteRecord() – Deletes the current record from the database.
- deleteMultiple() – Deletes all records in the result set without iterating. Important: deleteMultiple() does NOT trigger Business Rules on each record.
6. Encoded Queries
Instead of chaining multiple addQuery calls, you can use an encoded query string:
var gr = new GlideRecord('incident');
gr.addEncodedQuery('priority=1^stateNOT IN6,7');
gr.query();
Encoded queries are useful because you can copy them directly from a list filter's URL or breadcrumb in the ServiceNow UI.
7. Important Methods to Know
- addQuery(field, operator, value) – Adds a condition. The operator is optional; default is '='.
- addOrCondition(field, operator, value) – Adds an OR condition to an existing query condition.
- addEncodedQuery(query) – Adds a query using an encoded query string.
- addNotNullQuery(field) / addNullQuery(field) – Filters for non-empty or empty fields.
- orderBy(field) / orderByDesc(field) – Sorts results ascending or descending.
- setLimit(n) – Limits the number of records returned.
- getRowCount() – Returns the number of records in the result set (use cautiously for performance).
- getValue(field) – Returns the raw string value of a field.
- getDisplayValue(field) – Returns the display value (e.g., a user's name instead of their sys_id).
- setValue(field, value) – Sets a field value.
- setWorkflow(false) – Prevents Business Rules from running during update/insert/delete operations.
- canRead() / canWrite() / canCreate() / canDelete() – Checks ACL permissions for the current record.
- hasNext() – Returns true if there are more records to iterate through without advancing the pointer.
8. GlideRecord vs. GlideElement
A common source of confusion: when you access gr.field_name, you get a GlideElement object, not a primitive string. This matters when:
- Comparing values: use gr.getValue('priority') == '1' or gr.priority == 1 (GlideElement overloads comparison).
- Passing values to other functions: always use gr.getValue('field') or gr.getUniqueValue() to get actual string values, especially for sys_id.
9. GlideRecord and Dot-Walking
You can traverse reference fields using dot-walking:
var gr = new GlideRecord('incident');
gr.addQuery('priority', 1);
gr.query();
while (gr.next()) {
gs.info(gr.caller_id.email);
}
Here, gr.caller_id.email walks from the incident to the user record referenced in caller_id and retrieves the email field.
10. Performance Considerations
- Always use setLimit() if you only need a small number of records.
- Avoid using getRowCount() on large tables; consider using GlideAggregate instead.
- Use setWorkflow(false) carefully; it suppresses Business Rules, which may have unintended consequences.
- Prefer addEncodedQuery() over multiple addQuery calls for complex filters for readability and maintainability.
Exam Tips: Answering Questions on GlideRecord API
1. Know the Method Signatures
The CAD exam frequently presents code snippets and asks you to predict the outcome. Memorize the exact method names and their parameters. Pay special attention to methods like addQuery() (which can accept 2 or 3 parameters), get(), and addOrCondition().
2. Understand the Difference Between get() and query()/next()
A very common exam question pattern involves choosing between gr.get(sys_id) for a single record versus the addQuery → query → while(next) pattern for multiple records. Remember that get() returns a boolean and also moves the pointer to the found record.
3. Watch for GlideElement vs. String Traps
If a question asks what a field reference returns, remember that gr.field_name returns a GlideElement, not a string. Use getValue() for string values and getDisplayValue() for display values. Exam questions may present a comparison that fails because the developer used the GlideElement object directly in a string concatenation or comparison incorrectly.
4. Remember That deleteMultiple() Skips Business Rules
This is a favorite exam topic. If a question asks which delete method does NOT trigger Business Rules, the answer is deleteMultiple(). Conversely, deleteRecord() inside a while loop DOES trigger Business Rules for each record.
5. Be Careful With setWorkflow(false)
Questions may ask about suppressing Business Rules during batch updates. setWorkflow(false) is the correct method. Also note that autoSysFields(false) prevents updating system fields like sys_updated_on.
6. Encoded Queries Are a Common Topic
Know how to read and interpret encoded query strings. The exam may give you a URL or an encoded query and ask what records it returns. The caret symbol (^) represents AND, while ^OR represents OR, and ^NQ represents a new query (OR for the entire condition set).
7. Know Where GlideRecord Runs
GlideRecord is a server-side API. If a question presents a scenario where GlideRecord is used in a Client Script, that is incorrect (client-side should use GlideAjax to call a Script Include that uses GlideRecord). This is a very common trick question on the exam.
8. addOrCondition() Syntax
Understand that addOrCondition is called on the GlideQueryCondition object returned by addQuery, not on the GlideRecord object directly. For example:
var qc = gr.addQuery('priority', 1);
qc.addOrCondition('priority', 2);
9. Practice Reading Code Snippets
Many CAD questions present 4 code snippets and ask which one correctly accomplishes a specific task. Practice reading GlideRecord code quickly and identifying errors such as: missing query(), missing next(), using the wrong method, or operating on the wrong table.
10. Understand GlideRecord in Business Rules
In Business Rules, the current object is itself a GlideRecord. You do NOT need to query for the current record again. A common exam question tests whether you know that current.update() in a before Business Rule is unnecessary (and actually harmful, causing recursion), because the system automatically saves changes to current after a before Business Rule runs. Only use current.update() in an async Business Rule where the record has already been saved.
Summary
The GlideRecord API is the backbone of server-side development in ServiceNow. For the CAD exam, focus on understanding the full lifecycle of a query (instantiate → filter → execute → iterate → act), the differences between key methods, and common pitfalls like GlideElement vs. string values, missing query()/next() calls, and inappropriate use of deleteMultiple() or setWorkflow(false). Mastering these concepts will prepare you to confidently handle the many GlideRecord-related questions on the exam.
🎓 Unlock Premium Access
ServiceNow Certified Application Developer + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 3305 Superior-grade ServiceNow Certified Application Developer practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- CAD: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!