I have a table which contains IP addresses, such as 184.108.40.206. I want to display the table sorted by IP address (which is the primary key, a string), but unfortunately 220.127.116.11 will appear before 18.104.22.168!
The general solution to sorting strings of numbers of different lengths is to concatenate each of them onto the right end of a string of enough zeroes, and then take a substring of the desired length from the right.
For example, if we concatenate '123', '45', and '6' onto '00', we get '00123', '0045', and '006'. If we then take the rightmost 3 characters, we get '123', '045', and '006'. This is the strategy we shall apply to the IP numbers.
IP numbers contain four groups of digits, each of which can be between 1 and 3 digits long. We need a way to search a string or substring looking for the first occurrence of a specific character, in this case a period. We also need to pull substrings out, pad them with zeroes where necessary, and take the rightmost three characters to sort on. Each of the four groups can vary in size, so this will get tricky.
Standard SQL provides the SUBSTRING and POSITION functions, but these aren't supported by every database. For the following examples, I'll use Microsoft Access syntax, and the MID, INSTR, and RIGHT functions -- MID and RIGHT are special versions of SUBSTRING, and INSTR performs the POSITION function.
Let's get the first group of digits. We need a substring, starting at the very first character on the left, and going up to the last character before the first period --
MID( IPno , 1 , INSTR(IPno,'.')-1 )
INSTR(IPno,'.') returns the position of the first period, which will be 2, 3, or 4, depending on whether the first group of digits is 1, 2, or 3 digits long. The MID function starts at the first character of IPno, and goes for a length equal to the position of the first period minus 1, i.e. up to the last character before the period.
Once we have pulled out the digits of the first group, we need to pad them on the left with zeroes and take the rightmost 3 characters --
RIGHT( '00' & MID( IPno , 1 , INSTR(IPno,'.')-1 ) , 3 )
From here on it gets messier. To pull out the second group of digits, we have to start one character to the right of the first period, search for the next period in that substring, and then pull out the second group like this --
MID(IPno ,INSTR(IPno,'.')+1 ,INSTR(MID(IPno ,INSTR(IPno,'.')+1) ,'.')-1)
Notice that the length parameter, which determines how long a substring we're getting, is based on the position of the second period.
This response is continued.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.