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


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.


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('')
  3.     INSERT #IpAddresses VALUES('')
  4.     INSERT #IpAddresses VALUES('')
  5.     INSERT #IpAddresses VALUES('')
  6.     INSERT #IpAddresses VALUES('')
  7.     INSERT #IpAddresses VALUES('')
  8.     INSERT #IpAddresses VALUES('')
  9.     INSERT #IpAddresses VALUES('')
  10.     INSERT #IpAddresses VALUES('')

Just do a select to see what the data looks like

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


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

  1. SELECT * FROM #IpAddresses


When we use convert everything works as expected

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


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

Part of SQL Server Programming Hacks

Section Handy tricks

170 Rating: 2.3/5 (104 votes cast)