Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL field data type for IPv4 addresses

Tags:

sql

postgresql

ip

What is the correct data type for IPv4 addresses in PostgreSQL?

I heard about inet, but never used it.

I need to perform SELECT queries like SELECT ... WHERE ip = '99.88.99.88' and it should support the output of human readable format (by human readable I mean '99.88.99.88').

It would be nice to have the ability to SELECT the IP addresses by there subnet.

Thanks for any suggestions in advance!

like image 808
Aley Avatar asked Mar 13 '13 11:03

Aley


People also ask

What is data type for IP address in SQL Server?

As with MS SQL Server you can store IP address, both IPv4 and IPv6, either as varchar or as numeric. As already mentioned, the binary representation is much more preferable than any other as it reflects the true nature of an IP address. SELECT (split_part('192.168. 1.1', '.


1 Answers

The built-in cidr and inet types will do what you want and provide suitable operators:

regress=> SELECT '192.168.1.19'::inet << '192.168.1.0/24'::cidr;
 ?column? 
----------
 t
(1 row)

See the PostgreSQL documentation on network datatype operators and functions and on the network datatypes.

Limited index support is provided for the cidr and inet types; in particular, 'address in range' type queries are turned into range queries at least where the address is a constant. See this (rather old) thread.

See also Chris's point re ip4r.

like image 103
Craig Ringer Avatar answered Nov 11 '22 02:11

Craig Ringer