orderBy() vs orderByDesc() – ServiceNow

Both orderBy() and orderByDesc() are used to sort out query results before iterating and using the returned data using next() function in ServiceNow.

Usage of orderBy() and orderByDesc() method

  1. Both of them accept single argument
  2. That argument would be the back-end name or dictionary name of the table column to be used.

For Example, take an example of “Created on” field on change request table. Dictionary column name of this field is sys_created_on.

var grchg = new GlideRecord('change_request');
grchg.addQuery('sys_id', current.change_request);
		grchg.query();
if(grchg.next()){
     var grtask = new GlideRecord('change_task');
     grtask.addQuery('change_request', grchg.sys_id);
     grtask.orderBy('sys_created_on');
 // It will pick oldest task
     grtask.orderBy('sys_created_on');
 //It will pick recently opened task
     grtask.setLimit(1);
     grtask.query();
     if(grtask.next()){
	if(grtask.sys_id == current.sys_id && grchg.state == -2){
	     grchg.state = -1;
		}		
	}

Leave a Reply

Your email address will not be published. Required fields are marked *