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!
http://www.postgresql.org/docs/current/static/datatype-net-types.html having field of
inet
type it is only what you need.The built-in
cidr
andinet
types will do what you want and provide suitable operators:See the PostgreSQL documentation on network datatype operators and functions and on the network datatypes.
Limited index support is provided for the
cidr
andinet
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
.I want to add that the built-in types are quite powerful, and that's where you should start. However if you need GIN indexing, check out http://pgfoundry.org/projects/ip4r/
A case for ip4r (why I started using it) might be if you need to store CIDR blocks and make sure that no block contains any other block. Since this requires GIN indexing, you have to go with ip4r rather than the built-in types.