user301089
user301089

Reputation: 115

Order by in Postgresql to sort IP address?

I wish to sort a list of IP address.

Is there any function in Postgresql to use with the order by like INET_ATON in MySql ?

My current IP is on string format.

Upvotes: 6

Views: 5324

Answers (2)

peterreilly
peterreilly

Reputation: 11

I had to do something similar with IPv4 addresses stored as integers in a table, and was able to use the '0.0.0.0'::inet + num trick.

So where devaddr is a column in a table interface I did:

select  distinct ('0.0.0.0'::inet + devaddr) as addr from interface order by addr;

Upvotes: 0

Frank Bollack
Frank Bollack

Reputation: 25186

You can order your IP address column IP_Address with something like this:

SELECT * FROM MyTable ORDER BY inet(IP_Address)

See the documnetation for further reference.

Edit:

This is actually not a function but a type cast to the postgres integrated type for IP addresses.

Upvotes: 12

Related Questions