What is the best way to replace getRowCount in scripts for simple record counts?

Marcel H_
Tera Guru

I've seen mention of recommendations/best practices to not use getRowCount in scripts, and instead use GlideAggregate and ('COUNT') to quickly get a count to improve script performance. I'm not sure if that's really applicable in all cases and would like to know how others might handle something like: 

if (itemsr.getRowCount() > 1) {

I don't know if there's much, if any performance to be gained if we're just trying to find out if the count is > 1, but I'm not 100% sure. Below is the rest of the script block for reference. Any recommendations are greatly appreciated!

    getActiveCatalogItems: function () {
        var items = [];
        var catItem = new GlideRecord('sc_cat_item');
        catItem.addEncodedQuery("active=true");
        catItem.orderBy(name);
        catItem.query();
        
        while (catItem.next()) {
            var itemsr = new GlideRecord("item_option_new");
            itemsr.addQuery('cat_item', catItem.sys_id);
            itemsr.addQuery('type', 'NOT IN', '20,24,19');
            itemsr.query();
            if (itemsr.next()) {
                if (itemsr.getRowCount() > 1) {
                    var obj = {};
                    obj.name = catItem.name.toString();
                    obj.sys_id = catItem.sys_id.toString();
                    items.push(obj);
                }
            }
        }
        return JSON.stringify(items);
    },
6 REPLIES 6

Hitoshi Ozawa
Giga Sage
Giga Sage

BTW, the script will result in an error because there's no variable named "name".

Change

catItem.orderBy(name);

to

catItem.orderBy('name');

Hitoshi Ozawa
Giga Sage
Giga Sage

I would avoid nesting GlideRecords in a while loop and use GlideAggregate.

getActiveCatalogItems: function() {
    var items = [];
    var itemsr = new GlideAggregate('item_option_new');

    itemsr.addQuery('cat_item.active', 'true');
    itemsr.addQuery('type', 'NOT IN', '20,24,19');
    itemsr.addAggregate("COUNT");
    itemsr.groupBy('cat_item.sys_id');
    itemsr.groupBy('cat_item.name');
    itemsr.query();
    while (itemsr.next()) {
        if (itemsr.getAggregate('COUNT') > 1) {
            var obj = {};
            obj.name = itemsr.getValue('cat_item.name').toString();
            obj.sys_id = itemsr.getValue('cat_item.sys_id').toString();
            items.push(obj);
        }
    }
    items = items.sort(function(item1, item2) {
        if (item1.name > item2.name) return 1;
        if (item1.name < item2.name) return -1;
    });
    return JSON.stringify(items);
}