OBLYTECH Logo
OBLYTECH Logo
ServiceNow Encoded Query Explained
Home / Guides, Services and Solutions / Concepts Explained / ServiceNow Encoded Query Explained

ServiceNow Encoded Query Explained

What an Encoded Query Is

An Encoded Query is a way to filter records in ServiceNow using a specific syntax. Instead of building filters through a graphical interface by clicking fields and choosing conditions, you write a query in text format. Encoded queries are more powerful than graphical filters for complex conditions. They are used in reports, list views, automation, and APIs to find exactly the records you need.

Encoded Query syntax looks like: field_name=value or field1=value1^ANDfield2=value2. The caret (^) means AND. You can also use OR, NOT, and comparison operators like > for greater than and < for less than. Encoded queries are compact and powerful once you learn the syntax.

Where Encoded Queries Are Used

List views use encoded queries to filter records. Instead of clicking field values to add filters, you can paste an encoded query to define exactly which records appear. Reports use encoded queries to select which records the report includes. Automation uses encoded queries to find incidents that meet certain conditions and take actions on them. APIs use encoded queries to fetch specific records from the database.

Some ServiceNow features accept only encoded queries; they do not have graphical filter builders. If you need a complex filter with multiple conditions, encoded queries give you the control graphical interfaces do not. Learning encoded query syntax is valuable for anyone doing serious work in ServiceNow.

A Worked Example

You want to find all high-priority incidents assigned to a specific team that are still open. Using a graphical filter, you would click multiple fields and select multiple conditions. Using an encoded query, you write: Using an encoded query, you write one line such as priority=1^assignment_group=GROUP_SYS_ID^stateIN1,2, where GROUP_SYS_ID is the team’s sys_id and the state values are the stored numbers your instance uses for its open states. This single query line replaces several graphical filter clicks.

Another example: find all change requests created in the last seven days with a type of emergency or urgent. The query is: typesINemergency,urgent^sys_created_on>javascript:gs.dateAdd(new GlideDateTime(),’d’,-7). This is complex to express graphically but straightforward as an encoded query.

A third example: find configuration items with critical criticality that do not have an owner assigned. The query is a criticality condition joined to an empty-owner test, for example criticality=1^owned_byISEMPTY, where the criticality field and its stored values depend on your CI class and instance. This filtering is impossible graphically without multiple conditions and special handling for empty fields.

Common Operators and Syntax

Comparison operators include = (equals), != (not equals), > (greater than), < (less than). Logical operators include ^ (AND) and ^OR (OR). The IN operator matches any of several stored values in a comma-separated list: stateIN1,2,3, where the numbers are the stored choice values on your instance. The ISEMPTY operator finds records where a field has no value. The CONTAINSoperator does substring matching: short_descriptionCONTAINSerror.

Queries can reference related table fields using dot notation: incident.caller_id.company_id=your_company_id. This finds incidents where the caller works for a specific company without requiring a join in traditional SQL. Queries can use functions like javascript:gs.dateAdd() to calculate dates dynamically.

Building and Testing Queries

Learning encoded query syntax takes practice. Start with simple queries using = and basic fields. Add complexity gradually as you become comfortable. When building queries, test them in a safe context first: apply the query to a list view to see results before embedding it in an automation or report. Small mistakes in query syntax can produce unexpected results or no results at all.

ServiceNow provides query builders that generate encoded queries as you click. For complex queries, using the builder to start and then refining the resulting query is often faster than writing from scratch. Documentation on query syntax is available in ServiceNow’s help system and in the community.

Advanced Techniques and Performance Considerations

As you become proficient with encoded queries, you can tackle complex scenarios. Encoded queries have no parentheses for grouping; to combine separate blocks of conditions with OR, put ^NQ between the blocks, as in active=true^priority=1^NQstate=6. This creates more sophisticated filters than simple AND/OR chains.

Query performance matters in production. Complex queries with many conditions or functions (like javascript:gs.dateAdd) may run slowly against large tables. Test queries on production-sized data before embedding them in critical automation. Use indexes on frequently filtered fields to improve query performance.

Some queries reference system functions or other advanced features. For instance, the TODAYfunction inserts the current date, the MEoperator filters records owned by the current user, and the CURRENT_USERfunction inserts the logged-in user’s ID. These features make queries more dynamic and reduce the need to edit queries when contexts change.

When debugging queries, start by testing them in a safe list view to verify they return expected results before deploying to automation or reports. Read the resulting record set carefully: if a query is too permissive, it catches unwanted records; if it is too restrictive, it misses what you need.

Integration with Automation and Scripting

Encoded queries are essential for scripting in ServiceNow. GlideRecord scripts use encoded queries to fetch specific records. Instead of writing SQL, you write encoded queries in a platform-independent syntax. This isolates your scripts from database specifics and makes them more portable across ServiceNow instances.

Encoded queries are also essential for business rules, workflow conditions, and REST API filters. Any place you need to select records programmatically, encoded queries provide the syntax. Mastery of encoded query syntax directly translates to more powerful automation across the entire platform.

Where a query ends up doing the real work

An encoded query looks like a small string of text, but it becomes the rule that decides which records a report counts, which records an automation touches, and which records an integration returns. That makes it a piece of production logic even when it sits inside a list filter. The people who write these strings are often power users who learned the syntax from a colleague, and the people who rely on the results are managers who trust the numbers. Treat every query that drives a decision as something that needs an owner, a description of its intent, and a test that shows it returns the expected records.

The useful habit is to write the intent in plain words first. “Open high-priority incidents for the payments group that have no owner” is a sentence a reviewer can check. The encoded version of that sentence can then be compared with the sentence, condition by condition, rather than judged by how it looks.

Choosing where a query should live

The same query behaves differently depending on where it is stored and what reads it. The table sets out the common homes for a query and the risk that comes with each.

Where the query lives Who changes it What goes wrong when it changes How to protect it
Personal list filter The individual user Only that person’s view changes Keep personal filters out of shared dashboards
Shared list or saved filter Anyone with access to the list Every reader sees a different count from the same name Name the filter by its intent and record the owner
Report source condition A reporting owner A metric shifts without any change in the work Version the report definition and note the change
Automation or script condition A developer or platform owner Actions run on the wrong records, often in bulk Test on a copy of production volume before release
Integration or API filter An integration owner An external system receives too much or too little data Confirm the returned count with the receiving system

The row for automations deserves the most care. A query that returns a sensible number in a list can return a dangerous number when it drives a bulk update, because the list showed the first page while the automation acts on every match.

A method for building a query that will be relied on

  1. Write the intent as a sentence, and list each condition in that sentence as one line.
  2. Build the query one condition at a time, and check the count after each addition so you can see which condition changed the result.
  3. Check how empty values are treated. An empty field matches differently from a field set to a placeholder, and that difference is a common source of miscounts.
  4. Test the query as a standard user with the same access the automation or report will have, because a query run as an administrator can include records the real reader cannot see.
  5. Read a sample of the matched records by hand, including the edges, such as records at the boundary of a date range or records just outside a state.
  6. Save the sentence next to the query, along with the owner and the date the query was last checked against its intent.

Mistakes that produce plausible numbers

Many encoded query faults do not cause errors. They produce a count that looks reasonable. A date filter written with a relative expression can use the server’s clock rather than the reader’s time zone, shifting the counts for records created near midnight. An OR condition added to the end of an AND chain without parentheses changes the meaning of the whole query, so records that should have been excluded are returned. A condition on a reference field’s display value matches a different record when two names are similar. Each of these survives a casual glance and only shows up when someone compares the count with a second source.

The fix is a standing comparison. For any query that feeds a report or a target, keep a second way of finding the same records, such as a grouped view or a sample list, and reconcile the two when the query changes.

When a query is the wrong answer

A long encoded query that encodes a business process is a warning sign. If the rule has grown to a dozen conditions with nested logic, the process is probably better described as a decision table or a set of smaller rules, each with its own name. Queries are hard to review, hard to hand over, and easy to break. They suit precise selections and are poor at documenting why a selection exists. Where a query has to be explained in a meeting before it can be trusted, move the logic into a named, documented component that the query calls, or split it into two queries with clear purposes.

Also avoid queries for anything that must stay accurate as history changes. A query on current state will return different records next week, which is correct for a live queue and wrong for a monthly statistic. Use a stored snapshot or a reporting table for historical measures.

Signs that queries are healthy across the platform

Review the queries in use on a fixed schedule. Look for queries that refer to fields no one uses any more, for queries whose owner has left, and for queries that feed automations but are not listed anywhere an administrator would look. Compare the counts of the same concept across the places it appears, because a difference between two dashboards often means two queries have drifted apart. A healthy set of queries has one owner per query, one stated intent per query, and no two queries that claim to measure the same thing with different definitions.

Harder questions about query practice

Should a team reuse a query from another team’s report?

Copy the intent, not just the string. Reusing a query without knowing why it excludes certain records is how a new report inherits a condition that nobody can justify. Read the original intent, check that it matches the new purpose, and then build the new query with its own owner.

How do you stop people editing a shared filter in place?

Make the shared filter read-only for most users and give change rights to a named owner. Where that is not possible in the instance, publish the approved version with its intent on the list description and ask users to save personal copies rather than altering the shared one.

Is it worth tuning a query for speed before the data grows?

Yes for queries that run often or inside automations. Check that the fields in the main condition are indexed, avoid functions on indexed fields where a plain comparison will do, and test the run time at production volume rather than trusting a small sample. Revisit the query when the table has grown noticeably, because a query that was fast on a small table can become the slowest item on a dashboard.

Next step

That often exposes the condition that drifted.

The reference qualifier is the closest neighbour of this topic when queries limit what a user can pick from a reference field. For how queries feed integrations, the notes on scripted REST API design contracts cover what an external caller should be allowed to request.

Using encoded queries in scripts: addEncodedQuery, getEncodedQuery and the operators you will need

In a server script, addEncodedQuery() applies an encoded query string to a GlideRecord, and getEncodedQuery() returns the string for the conditions already built, which makes it the quickest way to see what a script is really asking for. Use addQuery() for one or two simple conditions and addEncodedQuery() once the filter has several conditions, a mix of AND and OR, or came from a list view.

A practical routine: build the filter in a list, right-click the filter breadcrumb and copy the query, paste it into the script, then log getEncodedQuery() and compare the two strings. If they differ, the script is not filtering what you think it is.

Operator Meaning Example
=, !=, >, >=, <, <= Compare a value priority=1
IN, NOT IN Match any listed value stateIN1,2,3
LIKE, STARTSWITH, ENDSWITH Match part of a string short_descriptionLIKEvpn
ISEMPTY, ISNOTEMPTY Test for a blank field assigned_toISEMPTY
^OR Join to the condition before it priority=1^ORpriority=2
^NQ Start a separate OR-ed query block active=true^NQstate=6
ORDERBY, ORDERBYDESC Sort the result ORDERBYDESCsys_created_on

Two habits prevent most surprises. First, ^OR attaches to the condition immediately before it, so a=1^b=2^ORc=3 means a is 1 and either b is 2 or c is 3. Second, test a query against a list before it goes into a report or script, and check the record count against what you expect. Queries that return too many records are harder to spot than queries that return none, because nothing looks broken. Add a limit while testing, and remove it only after the count makes sense.

Once a query matters to more than one person, keep it in one place, such as a script include or a saved filter, instead of pasting copies. The reporting and dashboards guides cover where the same filters show up in reports.

Encoded query operators, fields and stored values to check on your instance

An encoded query is a single text string of field, operator and value conditions joined by the caret, which ServiceNow saves for list filters and applies in scripts through addEncodedQuery. The value on the right is the stored value, not the label on screen, so choice fields such as state or priority are often matched by number.

The names below are common out-of-box values on the incident table and the GlideRecord API. Labels, choice values and defaults change between releases and instances, so check each one on your own instance and release before it goes into a report or script.

Piece What it does Example
STARTSWITH, ENDSWITH Match the beginning or end of a string field short_descriptionSTARTSWITHVPN
NOT LIKE, NOT IN Exclude a substring or a list of values stateNOT IN6,7
BETWEEN Match a range on a number or date field priorityBETWEEN1@2
Dot-walk Follow a reference field to the related table caller_id.active=true
addNullQuery, addNotNullQuery Script methods that test for a blank or filled field addNullQuery('assigned_to')

Example (hypothetical): a service desk lead wants open incidents of priority 1 or 2 that nobody owns. The string active=true^priorityIN1,2^assigned_toISEMPTY expresses that. After building the same filter in the list, call getEncodedQuery() in the script and compare the two strings. If the counts differ, compare the strings character by character before changing anything else.

Two limits matter before you build on these names. An encoded query has no parentheses, so separate groups of conditions are split with ^NQ. And a misspelled field name is not always reported: depending on instance settings, an invalid condition can be dropped or can return no rows, so compare the returned count with a list. Keep a shared string in one script include, and check that the report conditions built from it still match.

What is the difference between addQuery and addEncodedQuery in ServiceNow?

The addQuery method adds one condition per call, with the field, operator and value passed as separate arguments. The addEncodedQuery method takes a whole string of conditions at once. Use addQuery for one or two simple filters, and addEncodedQuery when the filter was built in a list or has several conditions.

Why does a state filter return nothing when I type the label?

Choice fields store a value, often a number, while the screen shows a label. Typing the label into the string compares it with the stored value, so nothing matches. Look up the stored value on the field’s choice list, or copy the query from a list filter and check it.

Can an encoded query use a field from a related record?

Yes. Dot-walking follows a reference field, so a condition such as caller_id.active=true filters incidents by a property of the caller’s user record. Each extra hop usually adds a join, so keep dot-walks short on large tables and test the run time at production volume.

Encoded Query Operators and How to Find Why a Filter Returns the Wrong Rows

An encoded query is a single text string built from conditions. Each condition is a field name, an operator and a value, and conditions join with ^. The string reads left to right and each condition narrows the result, unless you use ^OR or ^NQ between conditions. When a count looks wrong, the fastest repair is to test one condition at a time and watch how the count moves.

Operator What it matches Example pattern
= Exact value active=true
!= Anything except the value active!=true
IN Any value in a comma list priorityIN1,2
STARTSWITH Text that begins with the string short_descriptionSTARTSWITHVPN
ISEMPTY No value stored in the field assigned_toISEMPTY
ISNOTEMPTY Some value stored in the field assigned_toISNOTEMPTY
ORDERBYDESC Sorts results with the largest or latest value first ORDERBYDESCsys_created_on

The condition that drops the count to zero, or moves it unexpectedly, is the one to examine first.

Empty values need their own check. An ISEMPTY test does not catch a field holding a placeholder value. When a choice or state filter returns nothing, a common cause is that the string holds the label you see on screen instead of the stored value behind it. Confirm the stored values on your own instance and release, because they come from its choice list configuration.

Administrators can see rows that readers cannot. If the query drives a bulk update, compare the total count with what the first page of results shows, and treat any gap as a finding to explain.

If the same string feeds a dashboard, check the widget against the list view first, as the dashboard guide explains.

Store the working string with an owner and a one-sentence description beside it. The next editor can then compare the sentence with each condition. Who owns the source data is a separate question, covered in the source authority work.

Frequently asked questions

Why use encoded queries when graphical filters are simpler?

Graphical filters are simpler for basic conditions. Encoded queries are necessary for complex conditions, multiple ORs combined with ANDs, and negation. Some features only accept encoded queries. Once you learn the syntax, encoded queries are often faster to write than clicking through graphical interfaces.

What if I make a mistake in my encoded query?

ServiceNow returns an error or produces unexpected results. Test queries in a safe place first: use them on a list view to verify results before putting them in reports or automation. If results seem wrong, simplify the query to find which part is incorrect.

Can I use encoded queries in reports?

Yes. In the Report Builder, you can add conditions graphically or switch to encoded query mode and write the query directly. Encoded query mode gives you more control. Some complex report filters are only possible using encoded queries.

Talk to Oblytech

Planning, running or fixing a ServiceNow programme? Tell us where you are and we will suggest a sensible next step.

Contact us