GlideRecord Query Cheat Sheet ServiceNow Guru PDF
GlideRecord Query Cheat Sheet ServiceNow Guru PDF
GlideRecord Query Cheat Sheet ServiceNow Guru PDF
doubt if there’s a single concept in Service-now that is more valuable to understand than how to use GlideRecord methods to query, insert, update, and delete records in
I your system. These methods have a wide variety of uses and are found at the heart of many of the business rules, UI actions, and scheduled job scripts that are essential to
tie together your organization’s processes in your Service-now instance.
While the content of this post isn’t new information (additional examples can be found on the Service-now wiki), my aim is to provide a single page of information containing
some common examples of these methods as a reference. This is an excellent page to keep bookmarked!
Note: These methods are designed for use in server-side JavaScript (everything EXCEPT client scripts and UI policies). In some rare cases, it may be necessary to perform a
query from a client-side javascript (client script or UI policy). The few methods below that can be used in client-side JavaScript have been noted below.
Query
UPDATE: This same function applies to client-side GlideRecord queries! If at all possible, you should use an asynchronous query from the client as
shown below. See this post for details.
Can also be used in Client scripts and UI policies IF YOU ARE GETTING A RECORD BY SYS_ID.
The ‘get’ method is a great way to return a single record when you know the sys_id of that record.
You can also query for a specific field/value pair. The ‘get’ method returns the first record in the result set.
The ‘getRefRecord’ method can be used as a shortcut to query a record populated in a reference field on a record.
var caller = current.caller_id.getRefRecord(); //Returns the GlideRecord for the value populated in the 'caller_id' field
caller.email = '[email protected]';
caller.update();
‘OR’ Query
The standard ‘addQuery’ parameter acts like an ‘and’ condition in your query. This example shows how you can add ‘or’ conditions to your query.
Note that you can also chain your ‘OR’ condition as well, which is usually simpler
Inserts are performed in the same way as queries except you need to replace the ‘query()’ line with an ‘initialize()’ line as shown here.
//Create a new Incident record and populate the fields with the values below
var gr = new GlideRecord('incident');
gr.initialize();
gr.short_description = 'Network problem';
gr.category = 'software';
gr.caller_id.setDisplayValue('Joe Employee');
gr.insert();
Update
You can perform updates on one or many records simply by querying the records, setting the appropriate values on those records, and calling ‘update()’ for each record.
Delete
Delete records by performing a glideRecord query and then using the ‘deleteRecord’ method.
deleteMultiple Shortcut
If you are deleting multiple records then the ‘deleteMultiple’ method can be used as a shortcut
addEncodedQuery
I could build that encoded query string and use it in a query like this…
GlideAggregate
GlideAggregate is actually an extension of the GlideRecord object. It allows you to perform the following aggregations on query recordsets…
-COUNT
-SUM
-MIN
-MAX
-AVG
//Find all active incidents and log a count of records to the system log
var gr = new GlideAggregate('incident');
gr.addQuery('active', true
true);
gr.addAggregate('COUNT');
gr.query();
var incidents = 0;
if (gr.next()){
incidents = gr.getAggregate('COUNT');
gs.log('Active incident count: ' + incidents);
}
orderBy/orderByDesc
You can order the results of your recordset by using ‘orderBy’ and/or ‘orderByDesc’ as shown below.
//Find all active incidents and order the results ascending by category then descending by created date
var gr = new GlideRecord('incident');
gr.addQuery('active', true
true);
gr.orderBy('category');
gr.orderByDesc('sys_created_on');
gr.query();
addNullQuery/addNotNullQuery
‘addNullQuery’ and ‘addNotNullQuery’ can be used to search for empty (or not empty) values
getRowCount
Although ‘getRowCount’ isn’t available client-side, you can return the number of results in a client-side GlideRecord query by using ‘rows.length’ as shown here…
//Log the number of records returned by the query
var gr = new GlideRecord('incident');
gr.addQuery('category', 'software');
gr.query();
alert('Incident count: ' + gr.rows.length);
setLimit
chooseWindow
The chooseWindow(first,last) method lets you set the first and last row number that you want to retrieve and is typical for chunking-type operations. The rows for any
given query result are numbered 0..(n-1), where there are n rows. The first parameter is the row number of the first result you’ll get. The second parameter is the number
of the row after the last row to be returned. In the example below, the parameters (10, 20) will cause 10 rows to be returned: rows 10..19, inclusive.
setWorkflow
‘setWorkflow’ is used to enable/disable the running of any business rules that may be triggered by a particular update.
//Change the category of all 'software' incidents to 'hardware' without triggering business rules on updated records
var gr = new GlideRecord('incident');
gr.addQuery('category', 'software');
gr.query();
while
while(gr.next()){
gr.category = 'hardware';
gr.setWorkflow(false
false);
gr.update();
}
autoSysFields
‘autoSysFields’ is used to disable the update of ‘sys’ fields (Updated, Created, etc.) for a particular update. This really is only used in special situations. The primary
example is when you need to perform a mass update of records to true up some of the data but want to retain the original update timestamps, etc.
//Change the category of all 'software' incidents to 'hardware' without updating sys fields
var gr = new GlideRecord('incident');
gr.addQuery('category', 'software');
gr.query();
while
while(gr.next()){
gr.category = 'hardware';
gr.autoSysFields(false
false);
gr.update();
}
setForceUpdate
‘setForceUpdate’ is used to update records without having to change a value on that record to get the update to execute. ‘setForceUpdate’ is particularly useful in
situations where you need to force the recalculation of a calculated field for all records in a table or when you need to run business rules against all records in a table but
don’t want to have to change a value on the records.
This method is often used with ‘setWorkflow’ and ‘autoSysFields’ as shown below.
//Force an update to all User records without changing field values
var gr = new GlideRecord('sys_user');
gr.query();
while (gr.next()) {
false); //Do not run business rules
gr.setWorkflow(false
false); //Do not update system fields
gr.autoSysFields(false
true); //Force the update
gr.setForceUpdate(true
gr.update();
}
JavaScript Operators
The following operators can be used in addition to the standard field/value query searching shown above…
= Field value must be equal to the value supplied. addQuery('priority', '=', 3);
> Field must be greater than the value supplied. addQuery('priority', '>', 3);
< Field must be less than the value supplied. addQuery('priority', '<', 3);
>= Field must be equal to or greater than the value supplied. addQuery('priority', '>=', 3);
<= Field must be equal to or less than the value supplied. addQuery('priority', '<=', 3);
!= Field must not equal the value supplied. addQuery('priority', '!=', 3);
STARTSWITH Field must start with the value supplied. The example shown on the right will get addQuery('short_description', 'STARTSWITH', 'Error');
all records where the short_description field starts with the text 'Error'.
ENDSWITH Field must end with the value supplied. The example shown on the right will get addQuery('short_description', 'ENDSWITH', 'Error');
all records where the short_description field ends with text 'Error'.
CONTAINS Field must contain the value supplied anywhere in the field. The example shown addQuery('short_description', 'CONTAINS', 'Error');
on the right will get all records where the short_description field contains the text
'Error' anywhere in the field.
DOES NOT Field must not contain the value supplied anywhere in the field. The example addQuery('short_description', 'DOES NOT CONTAIN', 'Error');
CONTAIN shown on the right will get all records where the short_description field does not
contain the text 'Error' anywhere in the field.
IN Field must contain the value supplied anywhere in the string provided. addQuery('sys_id', 'IN',
'0331ddb40a0a3c0e40c83e9f7520f860,032ebb5a0a0a3c0e2e2204a495526dce');
INSTANCEOF Retrieves only records of a specified class for tables which are extended. For addQuery('sys_class_name', 'INSTANCEOF', 'cmdb_ci_computer');
example, to search for configuration items (cmdb_ci table) you many want to
retrieve all configuration items that are have are classified as computers. The
code uses the INSTANCEOF operator to query for those records.
Reply
Reply
Reply
Reply
There is. I usually use the ‘addEncocdedQuery’ method when dealing with date queries. You can build the query you want in a module or filter
definition to see what the encoded query should look like.
Reply
Thanks Mark!
I’ve scoured the SN wiki and this is a better summary of their glide record pages. I’m a newbie to SN and I must admit I’ve found the learning curve a bit
steep for customising SN, having come from other SaaS systems as Salesforce & Rightnow.
These systems let you use GUI’s to do most things and for more advanced customisation there is a scripting option. SN seems to be all scripting from the
get go with limited use of GUIs for configuration. It would be nice if their wiki included a clearer explanation on how Client Scripts, UI Policies, UI Actions,
Business Rules & Access Control all fits together…
Reply
Thanks for the comment. I think as you become more familiar with Service-now you’ll see that the majority of configurations are GUI-based or
require some pretty light scripting. I’m not that familiar with Salesforce & Rightnow so I couldn’t say how Service-now compares. Hopefully some
of the content here helps you to get going a little bit faster. I know that the SNC documentation team is really focusing right now on scripting
documentation so what you see on the wiki should be getting better by the day.
You might check out these forum links for some more information about SNC scripting basics. It gives some information from presentations I’ve
given in the past about how some of this stuff connects. http://community.service-now.com/forum/3480 http://community.service-
now.com/forum/3613
Reply
Gabe 11-02-2011, 15:10
Reply
*Fantastic* posting, Mark! Great to have all of these listed together – thanks!
Reply
In reference to the Or query – is there any documentation about what a QueryCondition object is, and what its other functions are?
Reply
@priscilla, there isn’t any other documentation about QueryCondition, but there’s really not much more to it either. The only real purpose of it is
to enable you to add an ‘Or’ condition to a GlideRecord query. There are a couple more examples that I could probably share though. I’ll see if I
can get something out next week.
Reply
A nice tip for the “addEncodedQuery” section: you can now right-click a Breadcrumb and select “Copy query” to get a copy of the encoded query.
Reply
Is there a way to get the display value from a SYS ID returned in a query?
example: I would like the below code to result in the display name for the requested_by and not the sys_id used to reference the user table.
var Req;
var gr = new GlideRecord("change_request");
gr.addQuery('number', current.sysapproval);
gr.query();
while
while(gr.next()) {
Req = gr.requested_by;
}
Reply
Since you’re dealing with a reference field you should be able to do something like this inside your while loop…
Req = gr.requested_by.getDisplayValue();
You can also just dot-walk to the field that contains the display value
Req = gr.requested_by.name;
Reply
Req = gr.requested_by.name;
Req = gr.requested_by.getDisplayValue();
Reply
gr.addQuery('number', current.sysapproval);
should be...
gr.addQuery('sys_id', current.sysapproval);
Reply
Ah, you are correct. I have corrected the query. Still, very odd when I use the following:
Req = gr.requested_by;
When using
Req = gr.requested_by.name;
I still get “undefined”.
I will keep working at it. Thanks for your time and help.
Reply
I find the encodedquery to be extremely helpful especially when my query includes things like created this week or created before a specific date. Then I
know for sure I have the right query string.
Question: If I run a GlideRecord query and then want to add another condition to the query and rerun it, is that possible?
Not that I would do the following but just as an example. The real code I’m doing has quite a few query conditions and I’m rebuilding the same query
multiple times just to add one more condition and it just seems inefficient.
EX:
var newArray = new Array();
var newArray2 = new Array();
var gr = new GlideRecord(‘incident’);
gr.addQuery(‘active’, true);
gr.query();
while(gr.next()){
if (gr.severity = ‘1’){
newArray.push(gr.number);
}
gr.addQuery(‘incident_state’, ‘6’);
gr.query();
while (gr.next()){
newArray2.push(gr.number);
}
Reply
One thing to note about updating a reference field to null is that it has to be done as described here:
Example 1
Source: http://wiki.servicenow.com/index.php?title=Setting_a_GlideRecord_Variable_to_Null
Reply
Thanks so much for posting this info -it is really helpful!. We are struggling with using AddQuery and AddORCondition to create an advanced query. Here
is an example of what we wre trying to accomplish..
(Where Priority is 1
AND IncidentState =6)
OR
(Where Priority = 2
AND Category = Software)
Reply
I struggle with ‘AddOrCondition’ sometimes too. I’ve found it helpful to use ‘AddEncodedQuery’ to manage those types of complex queries more
easily. By using that method, you can simply build the query filter in a standard list so that you can see exactly what you want, then right-click the
breadcrumb and select ‘Copy query’. Then you can just add that as an encoded query and not have to worry about the correct ‘AddOrCondition’
setup.
Reply
I’m also interested in doing nested AND conditions. Did you ever determine a way to do it. I’d prefer using an encoded query if possible. The only
other way I can think of doing it is to create two separate queries and then combine the results (not very pretty but easy enough I suppose).
Reply
Reply
I’m having trouble with setWorkflow. I’ve used it successfully before, but now it seems to be cancelling the update that it precedes. in a script action
(parm2 = sys_id of an inc and parm1 = display value of an assignment group), I have:
If I comment out “outage.setWorkflow(false),” I will see the update to the work notes. However, if i leave the line as is, i wont see the update. I definitely
do not want to trigger other business rules after this update, so im not sure what’s happening here. Anyone have any thoughts?
Reply
Hi Joe,
Don’t know if it’s still relevant, but I had the same issue.
Apparantly this is normal behaviour when using setWorkflow(false), the work_notes won’t be updated.
I’ve found a nice script include and a way to set the work notes alltogether even if setWorkflow(false) is applied.
KR,
Jef
Reply
I use this page quite a bit and just recently found out ServiceNow also offers a “NOT IN” operator, which has saved me several times.
Reply
Rajan Murkute 03-11-2015, 21:41
This cheat sheet covers the most frequently used GlideRecord operations. All explanations and examples are easy to follow. It saved me huge amount of
time which I may have spent looking through the Service-Now Wiki pages.
Reply
Reply