Service Now - Row Count for Table

Thursday Jan 9, 2020

If we need to get a count of rows for a table, with or without a filter we can use this.

This is useful to check that a record has some values in a related list.

Code

Here’s the code:

   function getRowCountForTable(tableName, filterField, filterValue) {
 		var aggregate = new GlideAggregate(tableName);
 		aggregate.addAggregate('COUNT');
 		if(filterField != undefined && filterValue != undefined){
 			aggregate.addQuery(filterField, filterValue);
 		}
 		aggregate.query();
 		if (aggregate.next()) {
 			return parseInt(aggregate.getAggregate('COUNT'));
 		} else {
 			throw ("Cannot count records in " + tableName);
 		}
 	}
 

Note that the filterField and filterValue are optional.