GlideAggregate
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
Want to learn this properly?
Our live, instructor-led ServiceNow Training covers this hands-on, with real projects and a certification path.
Check your understanding
Which method returns the computed number?
- A. getValue
- B. getAggregate
- C. getRowCount
- D. getDisplayValue
Show answer
B. getAggregate
getAggregate mirrors the arguments of addAggregate.
Main benefit of GlideAggregate over a loop?
- A. Shorter syntax
- B. Work happens on the database, not in memory
- C. It bypasses ACLs
- D. It writes to the log
Show answer
B. Work happens on the database, not in memory
The database does the counting and returns only the result rows.