Aircraft by Modelmodel-aircrafts.com

Glide Record Add Query: How to Filter Service Now Data

You use the addQuery method on a GlideRecord object to filter records before you retrieve them. This function restricts the data set so that only rows matching your specific criteria are returned, which is essential for performance and accuracy in ServiceNow scripts.

When you run a query without filters, the system returns every record in the table, which can quickly overwhelm your script or the user interface. By adding queries, you narrow the scope immediately. You must also remember that this method works within server-side scripts, such as business rules, scheduled jobs, or background scripts, rather than client-side code.

The Basic Syntax Structure

To add a query, you first initialize the GlideRecord with the table name. Then you call the addQuery method, passing in the field name and the value you want to match. Finally, you execute the query using the getRowCount or next method to retrieve the results.

The syntax looks like this:

var gr = new GlideRecord('table_name');
gr.addQuery('field_name', 'value');
gr.query();
while(gr.next()) {
  // process record
}

This structure ensures that the database engine applies the filter at the source. This is much faster than retrieving all records and filtering them in memory. Always close your GlideRecord objects when you are done to free up resources.

Handling Multiple Conditions

Often, you need to filter by more than one field. You can chain multiple addQuery calls together. By default, these conditions are combined with an AND operator. This means both conditions must be true for a record to be included.

For example, if you want records where the state is ‘New’ and the priority is ‘High’, you would write two separate addQuery lines. The system interprets this as a logical AND. If you need an OR condition, you cannot simply add another addQuery line. Instead, you must use the addEncodedQuery method or create a sub-query group.

Using addEncodedQuery allows you to pass a string that represents the entire query logic. This is useful when your query is complex or built dynamically from user input. It prevents SQL injection issues and keeps your code cleaner.

Using Sub-Query Groups

If you prefer not to use encoded strings, you can use the startGroup and endGroup methods. These methods allow you to mix AND and OR logic. You start a group, add your OR conditions, end the group, and then add more AND conditions outside the group.

This approach gives you full control over the boolean logic. It is particularly helpful when you have nested conditions that are difficult to express in a single encoded string. Remember that groups must be properly closed, or the query will fail.

Common Field Operators

The standard addQuery method uses an equals operator by default. It matches the exact value you provide. However, you often need other operators like greater than, less than, or contains.

To use different operators, you append the operator symbol to the field name. For example, to find records where a date is after a certain point, you would use ‘end_dateON’. The ‘ON’ stands for ‘On or After’. Other common suffixes include ‘GT’ for greater than, ‘LT’ for less than, and ‘CONTAINS’ for text searches.

Be careful with case sensitivity. Text fields usually respect the case of the value you pass, unless you use the CONTAINS operator. Date fields are compared based on the timestamp. Always verify the field type before choosing an operator. Using a date operator on a number field will cause an error.

Performance Considerations

Query performance is critical in ServiceNow. Every query hits the database, and slow queries can impact the entire instance. To keep your queries fast, always index the fields you use in your filters.

If you frequently filter by a custom field, ensure it has an index. Without an index, the database must scan every row in the table. This becomes exponentially slower as the table grows. Check the table schema to see which fields are indexed by default.

Avoid querying large tables without limits. Even with a good query, returning thousands of records can cause timeouts. Use the setLimit method to cap the number of results. This is especially important in user-facing scripts where you do not want to flood the screen with data.

Debugging Your Queries

If your query returns unexpected results, log the query string. You can access the query string using the getQuery method on the GlideRecord object. This shows you exactly what the system is sending to the database.

Compare the logged query with your expectations. Look for missing quotes or incorrect field names. You can also test the query in the Application Navigator by navigating to the table and using the filter navigator. If it works there but not in your script, check your script context and permissions.

Security and Permissions

GlideRecord respects ACLs (Access Control Lists). If a user does not have read access to a field, the query will ignore that field. This means you cannot bypass security by crafting a clever query.

Always run your scripts in the correct security context. Background scripts run as the admin user by default, which might give you access to data that regular users cannot see. When testing, switch to a regular user role to ensure your query works for everyone.

Never trust user input directly in your queries. Sanitize all inputs to prevent injection attacks. Use the addEncodedQuery method with pre-built templates whenever possible. This reduces the risk of malicious code being executed.

Best Practices for Maintenance

Keep your queries simple and readable. Break complex logic into named variables. This makes it easier for other developers to understand your intent. Comment your code to explain why you chose specific filters.

Regularly review your queries for unused fields. If you filter by a field that is no longer relevant, remove it. This simplifies the query and improves performance. Also, monitor query logs to identify slow-running scripts. Optimize these scripts by adding indexes or refining the logic.

Test your queries in a development instance before deploying to production. Use realistic data volumes to simulate performance. Catch errors early to avoid disruptions in live environments. Consistent testing ensures reliability and stability across your ServiceNow platform.

Related

Published 1 December 2026. Found an error? Tell us.