Count records with GlideAggregate, not getRowCount()
Get record counts, totals per group and simple statistics in one database query instead of loading every row into memory.
October 1, 2026 · #glideaggregate #performance #reporting
getRowCount() runs the full query and loads the result set just to tell you its size. GlideAggregate asks the database to count, which stays fast as tables grow.
var RecordCounter = Class.create();
RecordCounter.prototype = {
initialize: function () {},
/** Total rows matching an encoded query. */
count: function (table, encodedQuery) {
var ga = new GlideAggregate(table);
if (encodedQuery) ga.addEncodedQuery(encodedQuery);
ga.addAggregate('COUNT');
ga.query();
return ga.next() ? parseInt(ga.getAggregate('COUNT'), 10) : 0;
},
/** { groupDisplayValue: count } for one field. */
countBy: function (table, field, encodedQuery) {
var result = {};
var ga = new GlideAggregate(table);
if (encodedQuery) ga.addEncodedQuery(encodedQuery);
ga.addAggregate('COUNT');
ga.groupBy(field);
ga.query();
while (ga.next()) {
result[ga.getDisplayValue(field) || '(empty)'] = parseInt(ga.getAggregate('COUNT'), 10);
}
return result;
},
type: 'RecordCounter',
};
// Usage
// var c = new RecordCounter();
// gs.info(c.count('incident', 'active=true'));
// gs.info(JSON.stringify(c.countBy('incident', 'priority', 'active=true')));
How it works
addAggregate('COUNT')turns the query into aSELECT COUNT(*)on the database.groupBy()returns one row per distinct value, each with its own count.getAggregate()returns a string, so convert it before doing maths.
Gotchas
- Use
getDisplayValue(field)for reference and choice fields, otherwise you get sys_ids and raw values. - Other aggregates (
SUM,AVG,MIN,MAX) take a field name as the second argument.
MIT licence. Provided as-is, without warranty. Test in a sub-production instance first.