GlideRecord syntax uses the new GlideRecord('table_name') constructor and the query() method to retrieve data. You must call next() inside a loop to process each record individually.
This approach is the standard way to access database records in Server-side scripting, such as Business Rules or Script Includes. It provides efficient filtering capabilities that translate directly into SQL queries on the backend.
The Core Structure
Every GlideRecord interaction follows a strict sequence of steps. First, you create an instance of the GlideRecord class for the specific table you want to access. This step initializes the object but does not yet fetch any data from the database.
Next, you apply filters using methods like addQuery(). These filters define which rows match your criteria. After setting all necessary conditions, you execute the query by calling the query() method. This sends the request to the database and populates the internal result set.
Finally, you iterate through the results. The next() method moves the cursor to the next row. Inside the loop, you can read fields using getValue() or modify them using setValue(). Always remember to check the return value of next() to ensure a record exists before accessing its fields.
Initialization and Filtering
To start, instantiate the object with the table name as a string argument. For example, to work with the Incident table, use 'incident'. Then, add your search criteria. You can chain multiple addQuery() calls to combine conditions with AND logic.
If you need OR logic, you must use the addOrQuery() method. This creates a sub-query group within your main filter. Be careful not to mix these incorrectly, as it changes how the database interprets your search parameters.
Processing Results Efficiently
Once the query executes, you enter a while loop controlled by gr.next(). This loop continues as long as there are more records to process. If no records match your filters, the loop body never executes.
Inside the loop, access field values safely. Use getValue('field_name') to retrieve data. This method returns null if the field is empty, preventing errors. Avoid direct property access like gr.field_name unless you are certain the field exists and is populated.
When modifying records, call update() at the end of the loop iteration. This saves changes back to the database. Failing to call update() means your changes are lost when the script ends.
Handling Large Data Sets
For tables with many records, consider performance implications. GlideRecord loads all matching records into memory by default. If you only need to count records or check existence, use aggregate methods instead of iterating through every row.
Use getRowCount() to get the total number of matching records without loading them. This is much faster than looping and counting manually. Similarly, getQuery().toString() allows you to inspect the generated SQL query for debugging purposes.
Common Pitfalls and Best Practices
A frequent mistake is forgetting to call query() after adding filters. Without this call, the object remains unpopulated, and next() will always return false. Another common error is modifying a record and then trying to update it again without resetting the state properly.
Always wrap your GlideRecord operations in try-catch blocks to handle potential runtime errors. Database timeouts or permission issues can occur unexpectedly. Logging these errors helps in troubleshooting later.
Remember that GlideRecord respects security roles. If the current user lacks access to a table, the query will return no results, even if records exist. Test your scripts with different user roles to ensure consistent behavior across the platform.
Debugging Queries
To debug, print the query string using gs.info(gr.getQuery()). This shows exactly what conditions were sent to the database. Compare this output with your intended logic to spot mismatches. Also, check the system logs for any warnings related to query execution times.
Concrete Example
Consider a scenario where you need to find all high-priority incidents assigned to a specific group. Start by creating the GlideRecord for the incident table. Add a query for priority equal to High. Add another query for the assignment group.
Execute the query. Loop through the results. For each incident, log the number and short description. This pattern works for any table, provided you adjust the table name and field names accordingly.
Here is the structure:
var gr = new GlideRecord('incident');
gr.addQuery('priority', '1'); // High
gr.addQuery('assignment_group', 'your_group_id');
gr.query();
while (gr.next()) {
gs.info('Incident: ' + gr.number);
}
This code snippet demonstrates the essential flow. Replace ‘your_group_id’ with the actual sys_id of the group you are targeting. Ensure you have the necessary permissions to view these records.
Extending Functionality
You can also sort results using orderBy() or orderByDesc(). Place these calls before query() to control the order of returned records. Sorting can impact performance on large tables, so use it judiciously.
Limiting results is another useful technique. Use setLimit(n) to restrict the number of records processed. This is helpful for testing or when you only need a sample of data. Combine limits with sorting to get the top N records based on specific criteria.
Finally, always close your GlideRecord objects when finished, especially in loops. While the platform handles garbage collection, explicit closure improves resource management in long-running scripts. Call gr.destroy() to release resources associated with the object.