SQL sort varchar

Handian Sudianto 5,706 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
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,432 questions
0 comments No comments
{count} votes

Accepted answer
  1. DBG 2,376 Reputation points
    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 116.5K Reputation points MVP
    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 Answers by the question author, which helps users to know the answer solved the author's problem.