GlideAggregate: Count, Sum, and Group Records Without Loading Them All

GlideAggregate lets you perform aggregate functions — COUNT, SUM, AVG, MIN, MAX — directly at the database level. No loops. No loading records into memory. If you are currently counting records with a GlideRecord loop, you are doing it the slow way.

What is GlideAggregate?

GlideAggregate is a server-side API that extends GlideRecord to add aggregate query support. It pushes the aggregation to the database (SQL level) rather than doing it in application server memory.

Basic COUNT example

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT');
ga.query();
if (ga.next()) {
  var total = ga.getAggregate('COUNT');
  gs.log('Total incidents: ' + total);
}

COUNT with a filter

var ga = new GlideAggregate('incident');
ga.addEncodedQuery('active=true^state=1');
ga.addAggregate('COUNT');
ga.query();
if (ga.next()) {
  gs.log('Open active incidents: ' + ga.getAggregate('COUNT'));
}

GROUP BY

Group by a field to get counts per category:

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT', 'category');
ga.groupBy('category');
ga.query();
while (ga.next()) {
  gs.log(ga.category + ': ' + ga.getAggregate('COUNT', 'category'));
}

SUM and AVG

var ga = new GlideAggregate('change_request');
ga.addAggregate('SUM', 'estimated_duration');
ga.addAggregate('AVG', 'estimated_duration');
ga.query();
if (ga.next()) {
  gs.log('Total hours: ' + ga.getAggregate('SUM', 'estimated_duration'));
  gs.log('Average hours: ' + ga.getAggregate('AVG', 'estimated_duration'));
}

HAVING clause (filter on aggregated results)

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT', 'assignment_group');
ga.groupBy('assignment_group');
ga.addHaving('COUNT', 'assignment_group', '>', 10);
ga.query();
while (ga.next()) {
  gs.log(ga.assignment_group.getDisplayValue() + ': ' + ga.getAggregate('COUNT', 'assignment_group'));
}

When to use GlideAggregate vs GlideRecord

Use GlideAggregate any time you need: a count of records, a sum or average of a numeric field, or counts grouped by a category. Use GlideRecord when you need to access individual record data.

The rule: if you are writing a GlideRecord loop just to count records, replace it with GlideAggregate immediately.

Want the complete reference?

This article is part of the NowSpectrum knowledge library. Browse all products for cheat sheets, interview prep, and deep-dive reference guides.

Browse All Products →