How to Query Table?

To query a table, first create a ServiceNow object for the table. This object is called a GlideRecord. To create a GlideRecord create the following script:

var target_table = new GlideRecord('incident');
target_table.query(); // Issue the query to the database to get all records
while(target_table.next()) {
    // add code here to process the incident record
}

This issues the query() to the database. Each call to next() would load the next record. If we wanted to find all incidents where the State field is New.

var target_table = new GlideRecord('incident');
target_table.addQuery('state', 1);
target_table.query(); // Issue the query to the database to get relevant records
while(target_table.next()) {
    // add code here to process the incident record
}

Query Incident Table and Print data in Background Script:

var inc = new GlideRecord('incident');
inc.query();
while(inc.next()){
    gs.print('Incident Number: '+inc.number);
}

Query Incident Table and Print total Count in Background Script:

var count = 0;
var inc = new GlideRecord('incident');
inc.query();
while(inc.next()){
    count++;
}
gs.print('Number of Incidents : '+count );

Query Incident Table by State is New and Print data in Background Script:

var inc = new GlideRecord('incident');
inc.addQuery('state', 1);
inc.query();
while(inc.next()){
    gs.print('New Incident : '+inc.number);
}