inet Operators Match Addresses To Subnets
Store IPv4 and IPv6 subnets in inet columns, then use containment and overlap operators to match addresses.
Code
CREATE TABLE networks (
id int PRIMARY KEY,
label text NOT NULL,
subnet inet NOT NULL
);
INSERT INTO networks (id, label, subnet)
VALUES
(1, 'office', '10.0.0.0/8'),
(2, 'lab', '192.168.1.0/24'),
(3, 'vpn', '2001:db8::/32');
SELECT label,
masklen(subnet) AS prefix_length,
network(subnet) AS network_part,
host(subnet) AS first_address
FROM networks
ORDER BY id;
SELECT '10.20.30.40'::inet << '10.0.0.0/8'::inet AS inside_office,
'192.168.1.77'::inet <<= '192.168.1.0/24'::inet AS inside_or_equal,
'192.168.1.0/24'::inet && '192.168.1.128/25'::inet AS overlaps;
SELECT '2001:db8::1'::inet <<= '2001:db8::/32'::inet AS inside_v6;Inside the snippet
Several statements share this file — SELECT / INSERT / CREATE, with networks among the objects involved.
Mechanically, the statements are built from: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Using it
The networks table is the working surface here.
Key statements
SELECT '10.20.30.40'::inet << '10.0.0.0/8'::inet AS inside_office,
'192.168.1.77'::inet <<= '192.168.1.0/24'::inet AS inside_or_equal,
'192.168.1.0/24'::inet && '192.168.1.128/25'::inet AS overlaps;
SELECT label,
masklen(subnet) AS prefix_length,
network(subnet) AS network_part,
host(subnet) AS first_address
FROM networks
ORDER BY id;
INSERT INTO networks (id, label, subnet)
VALUES
(1, 'office', '10.0.0.0/8'),
(2, 'lab', '192.168.1.0/24'),
(3, 'vpn', '2001:db8::/32');
Interactive Tools for This Topic
IPv4 Subnet CalculatorCalculate network and broadcast addresses, netmask, wildcard, and usable host range from an IPv4 address in CIDR notation.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.
FAQ
- Which tables does the SQL touch?
- `networks` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.