mysql> SELECT ip FROM hostip ORDER BY ip; +-----------------+ | ip | +-----------------+ | 127.0.0.1 | | 192.168.0.10 | | 192.168.0.2 | | 192.168.1.10 | | 192.168.1.2 | | 21.0.0.1 | | 255.255.255.255 | +-----------------+
The preceding query produces output sorted in lexical order. To sort the ip values numerically, you can extract each segment and add zero to convert it to a number using an ORDER BY clause like this:
mysql> SELECT ip FROM hostip -> ORDER BY -> SUBSTRING_INDEX(ip,'.',1)+0, -> SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',-3),'.',1)+0, -> SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',-2),'.',1)+0, -> SUBSTRING_INDEX(ip,'.',-1)+0; +-----------------+ | ip | +-----------------+ | 21.0.0.1 | | 127.0.0.1 | | 192.168.0.2 | | 192.168.0.10 | | 192.168.1.2 | | 192.168.1.10 | | 255.255.255.255 | +-----------------+
However, although that ORDER BY produces a correct result, it involves a lot of messing around. A simpler solution is possible: use the INET_ATON( ) function to convert network addresses in string form directly to their underlying numeric values and sort those numbers:
mysql> SELECT ip FROM hostip ORDER BY INET_ATON(ip); +-----------------+ | ip | +-----------------+ | 21.0.0.1 | | 127.0.0.1 | | 192.168.0.2 | | 192.168.0.10 | | 192.168.1.2 | | 192.168.1.10 | | 255.255.255.255 | +-----------------+
If you’re tempted to sort by simply adding zero to the ip value and using ORDER BY on the result, consider the values that kind of string-to-number conversion actually produces:
mysql> SELECT ip, ip+0 FROM hostip; +-----------------+---------+ | ip | ip+0 | +-----------------+---------+ | 127.0.0.1 | 127 | | 192.168.0.2 | 192.168 | | 192.168.0.10 | 192.168 | | 192.168.1.2 | 192.168 | | 192.168.1.10 | 192.168 | | 255.255.255.255 | 255.255 | | 21.0.0.1 | 21 | +-----------------+---------+