Login or Sign Up to become a member!
LessThanDot Site Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Order IP Addresses

From Wiki

Jump to: navigation, search

If you have IP addresses in a varchar column and you need to sort them then you can use the parsename function, You will also need to convert each individual part to int or the sorting will be wrong

First create this table

  1. CREATE TABLE #IpAddresses(IP varchar(15))
  2.     INSERT #IpAddresses VALUES('12.12.12.12')
  3.     INSERT #IpAddresses VALUES('112.12.12.12')
  4.     INSERT #IpAddresses VALUES('12.12.112.12')
  5.     INSERT #IpAddresses VALUES('122.12.12.12')
  6.     INSERT #IpAddresses VALUES('122.122.12.12')
  7.     INSERT #IpAddresses VALUES('122.122.122.12')
  8.     INSERT #IpAddresses VALUES('122.122.122.122')
  9.     INSERT #IpAddresses VALUES('122.122.122.112')
  10.     INSERT #IpAddresses VALUES('122.122.122.123')


Just do a select to see what the data looks like

  1. SELECT * FROM #IpAddresses
  2.     ORDER BY IP


Output

112.12.12.12
12.12.112.12
12.12.12.12
122.12.12.12
122.122.12.12
122.122.122.112
122.122.122.12
122.122.122.122
122.122.122.123


Let's use parsename without converting to int, as you can see it is not ordered correctly

  1. SELECT * FROM #IpAddresses
  2.     ORDER BY PARSENAME(IP,4),PARSENAME(IP,3),PARSENAME(IP,2),PARSENAME(IP,1)


Output

112.12.12.12
12.12.112.12
12.12.12.12
122.12.12.12
122.122.12.12
122.122.122.112
122.122.122.12
122.122.122.122
122.122.122.123


When we use convert everything works as expected

  1. SELECT * FROM #IpAddresses
  2.     ORDER BY CONVERT(int,PARSENAME(IP,4)),
  3.     CONVERT(int,PARSENAME(IP,3)),
  4.     CONVERT(int,PARSENAME(IP,2)),
  5.     CONVERT(int,PARSENAME(IP,1))


Output

12.12.12.12
12.12.112.12
112.12.12.12
122.12.12.12
122.122.12.12
122.122.122.12
122.122.122.112
122.122.122.122
122.122.122.123



Contributed by: --SQLDenis 02:48, 31 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section Handy tricks

170 Rating: 2.7/5 (34 votes cast)