Use the GlideRecord object to fetch data from ServiceNow tables with methods like get, select, and query. The most common error is assuming that creating a record automatically saves it to the database; you must explicitly call insert or update.
The GlideRecord API is the standard way to interact with data in server-side scripts. It provides a structured interface for retrieving, modifying, and inserting records. You initialize the object with a table name, then apply filters to narrow your results. This approach is more efficient than writing raw SQL because it handles security and access controls automatically.
Initialization and Basic Retrieval
You start by instantiating the GlideRecord class. Pass the table name as a string argument. For example, to work with user records, you pass ‘sys_user’. Once initialized, the object is ready for configuration. You can set filters using addQuery or addEncodedQuery. These methods define which rows the database should return.
To retrieve a single record by its unique identifier, use the get method. Pass the sys_id value as an argument. If the record exists, the method returns true and populates the object with field values. If not, it returns false. This is the fastest way to fetch one specific row without scanning the entire table.
For multiple records, use the query method followed by an iterate loop. The query method executes the search against the database. The iterate function loops through each result. Inside the loop, you access fields using the getField method or direct property access. Always check if the record exists before accessing its data to avoid errors.
Filtering Strategies
Filters determine which records are returned. Use addQuery for simple conditions. You specify the field name, the operator, and the value. Common operators include equals, greater than, less than, and contains. You can chain multiple addQuery calls to create AND conditions. All conditions must be true for a record to match.
For complex logic involving OR conditions, use addOrCondition. Call this after your initial addQuery statements. Then add another addQuery block. The system treats the blocks as separate groups combined with OR. Be careful with precedence. The order of operations matters when mixing AND and OR logic.
Encoded queries offer a compact alternative. They use a specific syntax to represent filters. This is useful when passing filters between systems or storing them in variables. However, they can be harder to read and debug. Use them sparingly and prefer readable addQuery statements for clarity.
Modifying and Inserting Data
Retrieving data is only half the task. Often, you need to change existing records or add new ones. To modify a record, first fetch it using get or iterate. Then change the desired fields. Finally, call the update method. This writes the changes back to the database. Without update, the changes remain only in memory.
Inserting a new record requires a different workflow. Initialize the GlideRecord with the table name. Do not use get. Instead, set the fields directly on the object. Use setValue or assign the property. After setting all required fields, call insert. This creates a new row and generates a sys_id. The method returns the new sys_id upon success.
Always handle exceptions during insert and update. Database constraints may prevent the operation. Unique key violations or null constraints are common causes. Wrap your database calls in try-catch blocks. Log any errors for debugging. This prevents script failures from crashing the transaction.
Performance Considerations
Efficiency matters when working with large datasets. Avoid querying all records unless necessary. Always apply filters to reduce the result set. Use indexed fields in your queries. Indexed fields speed up lookups significantly. Unindexed queries scan the entire table and consume more resources.
Limits are important. Set a maximum number of records to process. Use setLimit to cap the results. This prevents memory exhaustion and timeout errors. If you need to process more records, break the job into batches. Process a subset, then move to the next batch.
Avoid nested queries inside loops. Fetching data inside a loop triggers a new database call for every iteration. This is slow and inefficient. Instead, fetch all needed data in a single query outside the loop. Store the results in a map or array. Access the stored data during iteration. This reduces database load dramatically.
Common Pitfalls and Corrections
Many developers make the same mistakes repeatedly. Understanding these helps you write better code. One frequent error is forgetting to call insert or update. Another is assuming that addQuery adds OR logic. Remember that chaining addQuery creates AND logic. Use addOrCondition for OR.
Accessing fields before fetching data is another trap. If you try to read a field on an uninitialized record, you get undefined values. Always ensure the record is loaded. Check the return value of get or verify the loop has entries. Never assume the data is there.
Security roles impact what you can see. GlideRecord respects user permissions. If your script runs under a user with limited access, some fields may be hidden. Use GlideSystem to impersonate a privileged user if needed. Or run the script in a context with appropriate roles. Check the documentation for role requirements.
Reference Table: Methods and Usage
| Method | Purpose | Returns |
|---|---|---|
| get | Fetches a single record by sys_id | Boolean (true/false) |
| query | Executes a filter and prepares results | GlideRecord object |
| iterate | Loops through query results | Void |
| update | Saves changes to an existing record | Void |
| insert | Creates a new record | String (new sys_id) |
| addQuery | Adds a filter condition | GlideRecord object |
Advanced Techniques
For bulk operations, consider using GlideAggregate. This class summarizes data without loading individual records. It calculates counts, sums, and averages efficiently. Use it when you need statistics rather than detailed records. This reduces memory usage and speeds up reporting tasks.
Debugging is essential. Use gs.log to write messages to the system log. Include variable values in your logs. This helps trace execution flow. Check the log level to ensure messages appear. Debugging tools in the developer mode provide additional visibility.
Testing your scripts is crucial. Use the Script Runner tool to execute snippets. Verify results in the database. Check for side effects. Ensure your code handles edge cases. Empty result sets, missing fields, and invalid inputs require special handling. Write robust code that fails gracefully.
Next Steps for Developers
Mastering GlideRecord takes practice. Start with simple queries and build complexity gradually. Experiment with different filter combinations. Profile your scripts to identify bottlenecks. Review best practices regularly. Stay updated with platform changes. New features may improve performance or add capabilities.
Join community forums to share knowledge. Read official documentation for updates. Participate in training sessions. Continuous learning keeps your skills sharp. The platform evolves, and so should your techniques. Apply these principles to build reliable integrations and automations.