Skip to content
IT Canvass
Development · Lesson

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

  1. Which method returns the computed number?

    • A. getValue
    • B. getAggregate
    • C. getRowCount
    • D. getDisplayValue
    Show answer

    B. getAggregate

    getAggregate mirrors the arguments of addAggregate.

  2. 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.

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.
CallWhatsAppEnquire