How To Use addQuery() With A GlideRecord

What Is The addQuery() Method? Every ServiceNow admin should know how to use the addQuery() method. It’s likely the first thing that an admin learns, when they get into scripting. They know that they have …


Buy The "ServiceNow Developer's Manual" Now

We've packed over a decade of ServiceNow Development advice, into a single e-book.

Buy It Now

What Is The addQuery() Method?

Every ServiceNow admin should know how to use the addQuery() method.

It’s likely the first thing that an admin learns, when they get into scripting.

They know that they have a table of data, and they know that they want to query it, but are unsure of how to build that query.

The addQuery() method is the most common method across the GlideRecord class, and is used as a query condition to find matches between fields and values. It is used in virtually every single GlideRecord query, because it’s so easy to use and understand. ServiceNow admins want to find matches on field values, and that’s where it comes into play.

Let’s cover how to use it below.

addQuery() In A GlideRecord Example

So addQuery() is a method and GlideRecord() is a class.

But what does it do?

Simply, it is used to specify query conditions when retrieving records from the database.

ServiceNow admins use addQuery() to select records from a table, based off of a field and value match.

Here is an example of using the addQuery() method in a GlideRecord query:

var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.addQuery('priority', 3);
gr.query();

while (gr.next()) {
  // process the incident record
}

This code creates a new GlideRecord object for the incident table, and then adds two query conditions using the addQuery() method:

  • active = true
  • priority = 3

The query() method is then called to execute the query and retrieve all incident records that match the specified conditions. The while loop iterates through the returned records and processes each one.

The addQuery() method takes three arguments:

  • A field name
  • A value to query for
  • An optional operator (e.g. =, !=, >, <, etc.)

For example, the following code would retrieve all incident records where the active field is true and the priority field is greater than 3:

var gr = new GlideRecord("incident");
gr.addQuery('active', true);
gr.addQuery('priority',  '>', 3);
gr.query(); 

How else have you used addQuery?



What Do You Think About This Article?

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] Use the addQuery method to filter the records that are returned by the GlideRecord. This method allows you to specify a field, an operator, and a value to filter the records by.We’ve covered how to really understand addQuery() here. […]

1
0
Would love your thoughts, please comment.x
()
x