What is an encoded query?
An encoded query is a string that represents one or more filter conditions on a ServiceNow table. You have already seen them — they appear in the URL when you filter a list view in the browser. For example:
active=true^stateIN1,2^assigned_toISNOTEMPTY
That same string can be passed directly to GlideRecord using addEncodedQuery().
Basic syntax rules
Conditions are separated by ^ (AND) or ^OR (OR). Each condition has the format: field_nameOPERATORvalue.
Common operators:
=— equals!=— not equalsIN— value is in a comma-separated listNOT IN— value is not in a listSTARTSWITH— string starts withCONTAINS— string containsISEMPTY— field has no valueISNOTEMPTY— field has a valueBETWEEN— numeric or date range>=,<=— greater/less than or equal
How to use addEncodedQuery()
var gr = new GlideRecord('incident');
gr.addEncodedQuery('active=true^stateIN1,2^assigned_toISNOTEMPTY');
gr.query();
while (gr.next()) {
gs.log(gr.number + ' - ' + gr.short_description);
}
Building encoded queries from the UI
The fastest way to build a complex encoded query is to use the list view filter, set up exactly the conditions you want, then right-click the breadcrumb at the top of the filter and select Copy query. Paste that string directly into your script.
OR conditions
Use ^OR to separate OR conditions:
gr.addEncodedQuery('state=1^ORstate=2^ORstate=3');
Equivalent to state IN 1,2,3 but useful when combining with other AND conditions on different fields.
Reference fields
For reference fields, use the sys_id of the referenced record as the value:
gr.addEncodedQuery('assigned_to=6816f79cc0a8016401c5a33be04be441');
To filter by a display value instead of sys_id, use the LIKE operator on the display field (dot-walked):
gr.addEncodedQuery('assignment_group.nameLIKENetwork');
Date filtering
Relative date operators work in encoded queries too:
gr.addEncodedQuery('sys_created_on>=javascript:gs.beginningOfLast7Days()');
gr.addEncodedQuery('opened_at>=javascript:gs.beginningOfThisMonth()');
Performance note
Encoded queries go directly to the database as SQL WHERE clauses. They are generally more performant than multiple addQuery() chains for complex conditions, because the query is planned in a single pass.