SQL sort by version "number", a string of varying length

For best results, refactor version number storage so that each section has it's own column: MajorVersion, MinorVersion, Revision, Build. Then the ordering problem suddenly becomes trivial. You can also build a computed column for easy retrieval of the full string.


In PostgreSQL you can do:

SELECT * FROM Requirements
ORDER BY string_to_array(version, '.')::int[];

This last ::int[] makes it convert string values into integers and then compare as such.


SELECT * FROM Requirements 
WHERE Requirements.Release NOT LIKE '%Obsolete%' 
ORDER BY cast('/' + replace(Requirements.ReqNum , '.', '/') + '/' as hierarchyid);

Tags:

Sql