Use GlideRecord to query, create, update, or delete records in ServiceNow tables. You instantiate the object with the table name, then chain methods like addQuery or setValue before calling query() or insert(). This approach is the standard way to manipulate data directly in server-side scripts.
GlideRecord Sets Up a Table Connection
The first step is creating an instance of the GlideRecord class for the specific table you want to access. You pass the table name as a string to the constructor. For example, to work with the Incident table, you would write var gr = new GlideRecord('incident');. This line does not fetch any data yet; it simply prepares the script to interact with that table.
Once the object is created, you can apply filters using the addQuery method. Each call to addQuery adds another condition to your search. These conditions are combined with a logical AND by default. If you need an OR condition, you must use addOrCondition immediately after the first query part. After setting up your filters, you must call gr.query() to execute the search against the database. Without this call, no records are retrieved.
Iterating Through Results
After running the query, you loop through the results using a while loop. The method gr.next() moves the cursor to the next record. It returns true if a record exists at that position and false when there are no more records. Inside the loop, you can read fields using gr.field_name or modify them using gr.setValue('field_name', 'value');.
GlideRecord Updates and Inserts Data
To change existing records, you find the record using the query process described above, modify the fields, and then call gr.update();. This writes the changes back to the database. To add a new record, you skip the query step. Instead, you set the field values directly on the GlideRecord object and call gr.insert();. The system automatically assigns the new sys_id and populates audit fields like created and updated timestamps.
You can also delete records using gr.deleteRecord();. This removes the current record pointed to by the cursor. Be careful when deleting inside a loop, as removing a record can affect the iteration. It is often safer to collect the sys_ids of records to delete first, then perform the deletions afterward.
GlideRecord Handles Performance Limits
ServiceNow enforces strict limits on how many records a script can process to protect system performance. By default, a GlideRecord query will only return the first few thousand records. If your query matches more records than the limit, the script stops processing further records. You can check the number of records processed using gr.getRowCount(); after the query executes.
To handle large datasets, you should use the setLimit() method to explicitly define how many records you need. If you need to process all matching records regardless of count, you might need to adjust the platform limits or use asynchronous processing. Always test your queries with realistic data volumes to ensure they stay within safe boundaries. Exceeding these limits can cause script timeouts or platform warnings.
Optimizing Query Efficiency
Efficient querying starts with choosing the right indexes. ServiceNow automatically indexes the primary key (sys_id) and commonly used fields. When you filter on indexed fields, the database retrieves records much faster. Avoid filtering on non-indexed fields whenever possible, as this forces the system to scan many more rows.
Another optimization technique is to retrieve only the fields you actually need. By default, a query loads all fields for each record, which consumes more memory. You can specify a list of fields to retrieve using gr.setOverrideFieldAccess(true); followed by gr.query(); and then manually accessing only those fields. This reduces the payload size and speeds up the script execution significantly.
GlideRecord Manages Permissions and Security
Security roles play a critical role in what a GlideRecord script can do. The script runs under the context of the user who triggered it, unless you explicitly change that context. If the user lacks permission to view or edit a table, the script will fail or return empty results. You can bypass some security checks by using gr.setDebug(true); to see detailed logs, but this does not grant unauthorized access.
For background jobs or system-level operations, you may need to run the script as a specific user with higher privileges. You can achieve this by using gs.getUserID(); to get the current user or switching contexts using gs.getSession().setUser();. However, changing user context should be done cautiously to avoid security vulnerabilities. Always ensure that sensitive data handling complies with your organization’s security policies.
Handling Errors Gracefully
Scripts can fail for various reasons, such as missing fields, invalid data types, or database connection issues. You should wrap your GlideRecord logic in a try-catch block to handle exceptions gracefully. This prevents the entire script from failing abruptly and allows you to log meaningful error messages. Use gs.error(); or gs.warn(); to record details about what went wrong.
When updating records, verify that the required fields are populated before calling update(); or insert();. Missing mandatory fields will cause the operation to fail. You can check for null values using standard JavaScript checks. Providing clear feedback helps administrators diagnose issues quickly without needing to dig through system logs.
GlideRecord Works With Complex Queries
Beyond simple equality checks, GlideRecord supports advanced query operators. You can use addQuery with operators like greater than, less than, or contains. For example, to find incidents opened in the last week, you would compare the open date against a calculated date value. Date comparisons require careful formatting to match the database expectations.
You can also combine multiple conditions using logical operators. While addQuery uses AND by default, you can switch to OR logic by adding an addOrCondition block. This is useful for finding records that match one of several criteria. Remember that each addOrCondition must be paired with a corresponding initial query. The structure of your query determines how the database evaluates the conditions.
Using Subqueries and Joins
While GlideRecord does not support traditional SQL joins, you can simulate relationships by querying related tables. For example, if you need data from the User table based on an Incident’s assigned_to field, you first query the Incident table, extract the user ID, and then query the User table. This two-step process ensures you get the correct related data.
For more complex scenarios, consider using Server Side Business Rules or Script Includes to encapsulate the logic. This keeps your main script clean and reusable. Encapsulating GlideRecord logic into functions makes it easier to test and maintain. You can call these functions from different parts of your application without duplicating code.