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!
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', '.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With