Sql-server – Natural (numeric) sort on string

sql server

I've got a table of data like so:

Process_Id  Stage_Id    Step_Id
P1          P1.5        P1.5.1
P1          P1.5        P1.5.10
P1          P1.5        P1.5.11
P1          P1.5        P1.5.12
P1          P1.5        P1.5.13
P1          P1.5        P1.5.14
P1          P1.5        P1.5.15

And as you can see it's not sorting naturally on the last number of the Step (as you or I would imagine it would be sorted in any other situation). This is of course because it's stored as a string.

Is it possible to have these numbers sort naturally? Perhaps ordering by a 'split' pseudo-column consisting of the split of Step_Id by '.'?

Thanks.

Best Answer

Assuming you can trust the last octet will always be a number:

ORDER BY CONVERT(INT, PARSENAME(Step_Id, 1));