GlideAggregate when to use if vs while in loop

corbettbrasing1
Mega Guru

I'd like to get some clarification on when its appropriate to use an if   or while loop get you use getAggregate();

The documentation has examples of both where there is an if and then others where there is a while loop.   Even in this article Count and Sum and Avg and Min and Max, Oh My! the 2 examples he uses to do the same thing, one has an if, the other has a while loop.

Is glide aggregate actually returning a result set that you need to loop through to constitute a while loop or is it a result set with 1 record?

1 ACCEPTED SOLUTION

Chuck Tomasi
Tera Patron

If you are using orderBy(), groupBy(), or distinct, then you will have multiple results and need to use a while(). If not, you use an if since there will only be one record to retrieve. You won't break anything if you use a while instead of if since the loop will only run once.


View solution in original post

3 REPLIES 3

Chuck Tomasi
Tera Patron

If you are using orderBy(), groupBy(), or distinct, then you will have multiple results and need to use a while(). If not, you use an if since there will only be one record to retrieve. You won't break anything if you use a while instead of if since the loop will only run once.


Thanks Chuck!   How do I request a documentation update to say what you just said.   I have looked in the documentation and it does not say what you just said anywhere in there.


sndangibbard
Mega Guru

You should use a while loop if you are using the GlideAggregate method groupBy()



https://developer.servicenow.com/app.do#!/api_doc?v=helsinki&id=r_GlideAggregate-groupBy_String



As you will getting back a set of several results, one for each group of records. If you are not using groupBy then you will get a single GA result back so you do not need to loop through but can use an if.