Force Related List sort order in ServiceNow

Have you ever opened a record and then gone on to look at the related list only to wish that it was ordered in a particular way such as by date, or by order, but isn't?

Have you wanted to force a related list in ServiceNow to sort by a particular field, disregarding the default sort and any custom user sort changes?

We've got you covered for this one!

Not only is it effective, but it's also much simpler than you would expect. We resolve our issue with a simple Before Query Business Rule.

A before query business rule is, you guessed it, a business rule that runs prior to a query being sent to the database. This is great as we can use it to modify any requests to the server for specific data, in a number of different possible ways.

  1. You could modify the query to add additional filters, for example adding Active is true as a requirement.
  2. Or you could change the sort order!!!

Let's now jump straight to number 2 above and modify that sort order and force our list to sort by the Order field in an Ascending fashion.

Before Query Business Rule

  1. Create a new Business Rule on the table in question (if your related list was full of incidents for example, you would create this on the Incident table).
  2. Set When to Before.
  3. Tick the checkbox next to Query.
  4. Tick the checkbox next to Advanced.
  5. Go to the Advanced Tab and enter a script similar to the following

Now you must decide how you want to sort your results, in our example we have decided to sort by the Order field, so we set up our query using "ORDERBYorder" where order above is the field name.

We then use the current object, and add our encoded query to it. This query gets applied to every call to the Incident Table in our particular use case, this can be modified using conditions and additional scripting logic.

(function executeRule(current, previous /*null when async*/) {

	var query = "ORDERBYorder";
	current.addEncodedQuery(query);

})(current, previous);

onBefore query business rule

How about ordering Descending? Almost identical, just add DESC to the query after ORDERBY.

(function executeRule(current, previous /*null when async*/) {

	var query = "ORDERBYDESCorder";
	current.addEncodedQuery(query);

})(current, previous);

onBefore query business rule

Happy sorting!