Below is a complete, self-contained example that shows how you can build an IPv4 type “by hand” in PostgreSQL while treating every octet as an 8-bit unsigned integer (0-255).
It includes
a domain that enforces the 0-255 range,
a composite type that keeps the four octets,
input / output helper functions and casts so that users can write normal dotted-quad literals,
a few demo queries.
⚠️ Reality check first
PostgreSQL already ships with the native types inet and cidr.
They store IPv4 and IPv6, understand subnet masks, can be indexed efficiently, etc.
Use them unless you really need the exercise shown below. 😉
──────────────────────────────────────────────────────────────
Step 1 – Domain for a single octet
──────────────────────────────────────────────────────────────
sql
-- 8-bit *unsigned* integer (Postgres' smallest integer is SMALLINT/INT2).
CREATE DOMAIN uint8 AS smallint
CHECK (VALUE BETWEEN 0 AND 255);
──────────────────────────────────────────────────────────────
Step 2 – Composite type that groups four octets
──────────────────────────────────────────────────────────────
sql
CREATE TYPE ipv4 AS (
o1 uint8,
o2 uint8,
o3 uint8,
o4 uint8
);
Right now you can already do
sql
SELECT ROW(192,168,0,1)::ipv4;
but you’ll probably want the more natural '192.168.0.1' literal.
That’s what the next step adds.
──────────────────────────────────────────────────────────────
Step 3 – Helper functions and casts
──────────────────────────────────────────────────────────────
Input (text → ipv4)
sql
CREATE OR REPLACE FUNCTION text_to_ipv4(p text)
RETURNS ipv4
LANGUAGE sql
IMMUTABLE STRICT
AS $$
SELECT ROW(
split_part(p,'.',1)::uint8,
split_part(p,'.',2)::uint8,
split_part(p,'.',3)::uint8,
split_part(p,'.',4)::uint8
)::ipv4;
$$;
Output (ipv4 → text)
sql
CREATE OR REPLACE FUNCTION ipv4_to_text(p ipv4)
RETURNS text
LANGUAGE sql
IMMUTABLE STRICT
AS $$
SELECT p.o1::text || '.' || p.o2 || '.' || p.o3 || '.' || p.o4;
$$;
Casts
sql
-- Allow assigning text to ipv4
CREATE CAST (text AS ipv4)
WITH FUNCTION text_to_ipv4(text)
AS ASSIGNMENT;
-- Pretty‐printing: ::text or explicit cast
CREATE CAST (ipv4 AS text)
WITH FUNCTION ipv4_to_text(ipv4)
AS ASSIGNMENT;
──────────────────────────────────────────────────────────────
Step 4 – Use it!
──────────────────────────────────────────────────────────────
sql
-- Table using the new type
CREATE TABLE demo_ips (
id serial PRIMARY KEY,
ip ipv4 NOT NULL
);
-- Insert with dotted-quad literal (works thanks to the cast)
INSERT INTO demo_ips(ip) VALUES
('10.0.1.5'),
('192.168.100.200');
-- Query it
SELECT id,
ip, -- composite representation
ip::text AS ip_pretty
FROM demo_ips;
Result:
code
id | ip | ip_pretty
----+---------------+--------------
1 | (10,0,1,5) | 10.0.1.5
2 | (192,168,100,200) | 192.168.100.200
──────────────────────────────────────────────────────────────
Extra goodies (optional)
──────────────────────────────────────────────────────────────
Network/host ordering, arithmetic, subnet operations… all must be coded manually if you need them.
Indexes: a B-tree on the composite type works but stores all four columns; you could pack the address into a 32-bit integer for faster searching.
If you only want four separate columns, you can skip the composite type and just use uint8 columns (oct1, oct2, oct3, oct4) in your tables.
──────────────────────────────────────────────────────────────
Takeaway
──────────────────────────────────────────────────────────────
Creating a custom IPv4 type is mostly an exercise in:
• defining a domain for 0-255,
• grouping four of them in a composite type, and
• adding convenient casts so users don’t have to write ugly ROW(...) literals.
For production work, the built-in inet/cidr types are almost always the better choice, but now you have a template if you ever need or want to roll your own. Happy hacking! 🐘
User
describe PostgreSQL inet and cidr types
Assistant
🐘 PostgreSQL’s built-in IP datatypes: inet & cidr
PostgreSQL ships with two native datatypes that understand both IPv4 and IPv6, know about subnet masks, can be indexed efficiently, and come with a rich set of operators & functions.
Type
What it stores
Typical literal
Host bits allowed?
Use-case in one line
inet
A full IP addressoptionally followed by a netmask.
'192.168.1.12/24' or '2001:db8::5'
Yes (can be anything)
“This exact host (and maybe I remember its mask, too).”
cidr
A pure network (address + mandatory mask).
'192.168.1.0/24'
No – host bits must be zero
“This subnet.”
1. Storage & size
Family
inet size
cidr size
Notes
IPv4
8 bytes
8 bytes
4 bytes for address + 1 byte family + 1 byte mask + 2 bytes padding
IPv6
20 bytes
20 bytes
16 bytes address + 1 + 1 + 2
Variable-length, but small enough that a billion rows still fit in an index comfortably.
2. Input & output formats
Postgres accepts most notations you’ll see in the wild:
A plain address cast to cidr raises an error because no mask is given.
3. Operators you’ll actually use
code
Operator Meaning Example (yields boolean)
--------- -------------------------- ----------------------------------
=, <, > normal ordering '10.0.0.1'::inet > '8.8.8.8'::inet
<< subnet **contains** subnet '10.0.0.0/8'::cidr << '10.1/16'
<<= contains or equals '10/8' <<= '10/8' -- true
>> contained-by '10.1/16'::cidr >> '10/8'
&& subnets overlap '10/8'::cidr && '10.1/16'
+ n, - n add / subtract integer '10.0.0.1'::inet + 5 -- 10.0.0.6
4. Built-in helper functions
Function
Purpose
Quick demo
family(addr)
4 for IPv4, 6 for IPv6
family('::1'::inet) = 6
masklen(addr)
current mask length
masklen('10/8') = 8
set_masklen(addr, m)
change mask
set_masklen('10.0.0.1'::inet, 24)
abbrev(addr)
shortest text form
'2001:0db8::1/64' → '2001:db8::1/64'
host(addr)
strip mask, host only
host('10.0.0.1/24') = '10.0.0.1'
network(addr)
return the cidr block
network('10.0.0.9/24') = '10.0.0.0/24'
broadcast(addr)
last address of block
broadcast('10.0.0.0/30') = '10.0.0.3'
text(addr)
implicit cast to text
'10/8'::inet::text = '10.0.0.0/8'
See \df *inet* or the manual for many more.
5. Indexing
• B-tree works for equality and ordering (=, <, >).
• GiST and SP-GiST options (btree_gist / inet_ops) support containment (<<, >>, &&) ‑ perfect for IP-in-subnet look-ups.
sql
CREATE EXTENSION btree_gist; -- once per database
CREATE TABLE hosts (
id serial,
ip inet NOT NULL,
PRIMARY KEY(id)
);
CREATE INDEX host_subnet_gist ON hosts USING gist (ip inet_ops);
6. Practical examples
1️⃣ Is an address inside a corporate network?
sql
SELECT ip
FROM hosts
WHERE ip << '10.0.0.0/8'::cidr;
2️⃣ All /24 subnets that overlap an existing block:
sql
SELECT DISTINCT network(ip) AS subnet_24
FROM hosts
WHERE network(ip) && '192.168.0.0/16';
3️⃣ Simple arithmetic – next IP:
sql
SELECT ip, ip + 1 AS next_ip
FROM hosts
ORDER BY ip
LIMIT 5;
7. When to choose which?
• Need individual hosts and subnets? → store as inet.
• Pure subnet catalog, never individual hosts? → cidr enforces correctness.
• Mixed table? Many use a single inet column and simply ensure subnets have the correct mask elsewhere.
8. Why you rarely need a custom IPv4 type
inet/cidr already give you:
✔ IPv4 & IPv6 in one column
✔ Mask awareness
✔ Rich operators
✔ Index support
✔ Tight storage (no 4-column “octet” tables)
Only roll your own if you have a very exotic requirement (e.g., different wire format, non-standard masks, etc.).