SQL sort varchar

Handian Sudianto 6,541 Reputation points
2025-01-31T01:09:17.6233333+00:00

i have table contain of ip address, how we can sort the ip address from .1 to .254?

If i sort by asc then the result is not sequence like below pic. After .1 then jump to .102 not to .2

The field using varchar,

User's image

SQL Server | Other
0 comments No comments
{count} votes

Answer accepted by question author
  1. DBG 11,531 Reputation points Volunteer Moderator
    2025-01-31T01:37:40.03+00:00

    Sorting would be easier if you store each octet in separate columns.


1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 128.7K Reputation points MVP Volunteer Moderator
    2025-01-31T22:49:25.08+00:00

    Here is a solution which I think is better than splitting the value into four:

    SELECT ip_address
    FROM  tbl
    ORDER BY convert(int, parsename(ip_address, 4)),
             convert(int, parsename(ip_address, 3)),
             convert(int, parsename(ip_address, 2)),
             convert(int, parsename(ip_address, 1))
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.