Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Accessing the last record in GlideCollection

RajanMurkute
Mega Guru

Using 'gr.next()' reads the first record in a glide_collection . But if I want to stat reading the records in reverse order (ie. reading the last record, first) how do I do that? Any suggestion will be appreciated. Thanks.

1 ACCEPTED SOLUTION

sachin_namjoshi
Kilo Patron
Kilo Patron
You need to use orderByDesc() like below

var gr = new GlideRecord ('incident');


gr.orderByDesc('sys_created_on');


gr.setLimit(1);


gr.query();


if (gr.next()){


   gs.print (gr.number + ' - ' + gr.sys_created_on);


}

Regards,
sachin

View solution in original post

9 REPLIES 9

sachin_namjoshi
Kilo Patron
Kilo Patron

You need to use orderByDesc() like below

 

var gr = new GlideRecord ('incident');

 

gr.orderByDesc('sys_created_on');

 

gr.setLimit(1);

 

gr.query();

 

if (gr.next()){

 

  gs.print (gr.number + ' - ' + gr.sys_created_on);

 

}

 

Regards,

sachin

sachin_namjoshi
Kilo Patron
Kilo Patron
You need to use orderByDesc() like below

var gr = new GlideRecord ('incident');


gr.orderByDesc('sys_created_on');


gr.setLimit(1);


gr.query();


if (gr.next()){


   gs.print (gr.number + ' - ' + gr.sys_created_on);


}

Regards,
sachin

Cody Smith _ Cl
Tera Guru

Before your query add 

gr.orderByDesc('sys_created_on');

 

Doc to OrderBy

 

If my answer was helpful, or solved your issue, please mark it as Helpful / Correct.
Thanks,
Cody

asifnoor
Kilo Patron

Hi,

Simply use orderByDesc in your code. here is the sample code to refer.

var gr = new GlideRecord('incident');

gr.orderByDesc(‘number');

gr.query();

if (gr.next()) {

  gs.info("Number is" +gr.number);

}

Mark the answer as correct or helpful if this helps.