Sorting IP addresses in Vertica

This blog post was authored by Jim Knicely.

Often times we store IP addresses in a VARCHAR column in a Vertica table. When querying the data and sorting by the IP address, we see that IP addresses are sorted by its VARCHAR value instead of its numeric value.

Fortunately Vertica has the INET_ATON function which returns an integer that represents the value of the address in host byte order, given the dotted-quad representation of a network address as a string. We can use it to properly sort our IP addresses!


dbadmin=> \d ip_addresses;
                                       List of Fields by Tables
Schema |    Table     | Column |    Type     | Size | Default | Not Null | Primary Key | Foreign Key
public | ip_addresses | ip     | varchar(15) |   15 |         | f        | f           |
(1 row)

dbadmin=> SELECT * FROM ip_addresses ORDER BY ip;
(9 rows)

dbadmin=> SELECT * FROM ip_addresses ORDER BY INET_ATON(ip);
(9 rows)

Have fun!

Sign In or Register to comment.