Skip to content
← All scripts
Script Includeglobal scopeReview before use · not yet release-tested

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 a SELECT 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.

Related scripts

Script Includescoped

Read system properties with types and defaults

A small Script Include that reads system properties as numbers, booleans or lists with safe defaults, so code never hardcodes sys_ids or thresholds.

#system-properties #configuration #best-practice

Fix scriptglobal

Find duplicate values in any table

List values that appear more than once in a field, such as duplicate user emails or CI serial numbers, using one aggregate query.

#glideaggregate #data-quality #duplicates