Development · LessonBy Praveen T, ServiceNow Trainer, 9 yrs · Published · ServiceNow · all levels
GlideAggregate
Count, sum and group records on the database instead of looping in script.
Quick answer
Count, sum and group records on the database instead of looping in script.
Key takeaways
- Use GlideAggregate for any count, sum or average
- Group on the database rather than in a loop
- orderByAggregate sorts by the calculated value
- A total count needs no groupBy at all
Why it exists
Looping a GlideRecord to count rows pulls every record into memory. GlideAggregate pushes the work to the database and returns only the numbers, which is the difference between a script that finishes in milliseconds and one that times out.
Counting and grouping
Add the aggregate, add a groupBy, then read the value per row.
var ga = new GlideAggregate('incident');
ga.addQuery('active', true);
ga.addAggregate('COUNT', 'priority');
ga.groupBy('priority');
ga.query();
while (ga.next()) {
gs.info(ga.priority + ': ' + ga.getAggregate('COUNT', 'priority'));
}Other aggregates
SUM, AVG, MIN and MAX work the same way, and orderByAggregate sorts by the computed value.
- getAggregate takes the same two arguments you passed to addAggregate
- Use setGroup(false) with a plain COUNT when you only need a total
- Aggregates respect ACLs when run in scoped code with the default security setting
Practice challenge
+0 XPStreak ×0
Question 1 of 2
Which method returns the computed number?
Frequently asked questions
When is a GlideRecord loop acceptable for counting?
When the result set is genuinely small and you already need the records for something else. Otherwise use GlideAggregate.
Does GlideAggregate honour access controls?
In scoped applications it applies the standard security checks. In global scope it depends on how the script runs, so treat aggregate output as privileged unless you have checked.