Sorting knowledge article by version

ViljamiK
Tera Contributor

I'm sorting kb articles by version number from ascending to descenting.  Articles aren't in the numeric order. Does Service Now sort the article versions from the first character, not from the whole number. See the screenshot for reference.

 

ViljamiK_1-1769771353450.png

 

1 ACCEPTED SOLUTION

sergiu_panaite
ServiceNow Employee

That happens because the version field is a reference to kb_version table and it is of String type. The database engine just orders them lexicographically where for example "13.0" comes before "3.0" alphabetically ("1" < "3").

 

Same can be demonstrated with a simple JavaScript that you can run in Background Scripts:

 

 

const versions = ["1.0", "12.0", "13.0", "2.0", "3.0"];

//Default sorting
//Outputs: 1.0, 12.0, 13.0, 2.0, 3.0
gs.info("Default sorting lexicographically: " + versions.sort());

//Sort numerically:
//Outputs: 1.0, 2.0, 3.0, 12.0, 13.0
gs.info("Sort numerically: " + versions.sort((a,b) => parseFloat(a) - parseFloat(b)));

 

 

This means you cannot get the numerical sorting in the current form. There are a few options, but not all of them are recommended:

 

1. You could create an additional field on kb_knowledge table that contains a copy of the version but as a Decimal type

2. You can change the field type of kb_version table, but since that is an OOB table it is not recommended.

 

Regards,

Sergiu

View solution in original post

1 REPLY 1

sergiu_panaite
ServiceNow Employee

That happens because the version field is a reference to kb_version table and it is of String type. The database engine just orders them lexicographically where for example "13.0" comes before "3.0" alphabetically ("1" < "3").

 

Same can be demonstrated with a simple JavaScript that you can run in Background Scripts:

 

 

const versions = ["1.0", "12.0", "13.0", "2.0", "3.0"];

//Default sorting
//Outputs: 1.0, 12.0, 13.0, 2.0, 3.0
gs.info("Default sorting lexicographically: " + versions.sort());

//Sort numerically:
//Outputs: 1.0, 2.0, 3.0, 12.0, 13.0
gs.info("Sort numerically: " + versions.sort((a,b) => parseFloat(a) - parseFloat(b)));

 

 

This means you cannot get the numerical sorting in the current form. There are a few options, but not all of them are recommended:

 

1. You could create an additional field on kb_knowledge table that contains a copy of the version but as a Decimal type

2. You can change the field type of kb_version table, but since that is an OOB table it is not recommended.

 

Regards,

Sergiu