GlideRecord orderBy
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎11-28-2018 05:09 AM
Good Eve all !
I have a short query regarding GlideRecord *orderBy* clause.
What happens when certain records are set on same order ?
Let's say we queried a custom table and added a condition to sort the data according to ascending order
of a field : *u_rank*.
Code Snippet :
var rec = new GlideRecord('u_plant_coorporates);
rec.orderBy('u_rank');
rec.query();
while(rec.next())
{
//do something
}
If there are 3 records set on same rank (let's say : u_rank=1 for all 3 records), then does it take only 1st record and skips rest of them ?
What if we want other records as well (set on the same u_rank) ?
Best Regards,
Puru
- Labels:
-
Scripting and Coding
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎01-09-2024 01:55 AM
The GlideRecord orderBy method in ServiceNow is used to sort the records in ascending order based on the specified column. If multiple records have the same value for the column specified in the orderBy method, all of these records will be returned, not just the first one. The order in which these records with the same value are returned is not guaranteed and may depend on other factors such as the order in which they were inserted into the database. Here's a summary of the key points: - The orderBy method sorts records in ascending order based on the specified column. - If multiple records have the same value for the specified column, all of these records will be returned. - The order of records with the same value is not guaranteed and may depend on other factors. - If you want to ensure a specific order for records with the same value, you can use the addOrderBy method to specify additional columns to sort by. - For example, rec.addOrderBy('u_rank'); rec.addOrderBy('sys_created_on'); will sort the records first by 'u_rank' and then by 'sys_created_on' for records with the same 'u_rank'. - This will ensure that all records are returned and in a predictable order. nowKB.com
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-02-2024 10:46 AM
If you need specific sorting behavior for tied records, you'll need to implement additional logic in your script.
var rec = new GlideRecord('u_plant_corporates');
rec.orderBy('u_rank');
rec.query();
var previousRankValue = null;
while (rec.next()) {
// Check if the current record has the same rank as the previous one
if (rec.u_rank != previousRankValue) {
// Handle the record, e.g., output to log or process it
gs.info("Record with u_rank " + rec.u_rank + ": " + rec.getValue('some_field'));
}
// Keep track of the previous rank value
previousRankValue = rec.u_rank;
}
