Network and geometric types
Overview
PostgreSQL inet represents host addresses with optional network prefixes; cidr represents networks and requires host bits outside the prefix to be zero. It also has planar point, box, polygon and circle types. SQLite lacks these native types. This lab uses Python ipaddress callbacks for address membership and ordinary numeric columns for planar coordinates.
First example
SELECT id,ct_in_net(addr,'192.0.2.0/24') FROM ct_device ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 1 ], [ 2, 1 ], [ 3, 0 ]]How it works
Compare IP addresses by parsed address and network semantics rather than textual prefixes; IPv6 has multiple equivalent spellings. The callback accepts a plain IPv4 or IPv6 host and a canonical network, returns NULL for NULL inputs, and rejects invalid strings. It returns false for mismatched families. For planar points, compare squared Euclidean distances to avoid a square root when only ordering or a radius test is needed. Coordinates here are arbitrary Cartesian units, not longitude/latitude; geographic distance needs an appropriate spatial reference system and algorithms.
Practical example
SELECT id,x*x+y*y AS distance_squared FROM ct_point WHERE x*x+y*y<=25 ORDER BY distance_squared,id;Observed SQLite result (rows in JSON):
[ [ 1, 0 ], [ 2, 25 ]]Practice and mistakes
Practice: find all devices in 192.0.2.0/24 and points within radius 5 of (0,0), including the boundary. Hint 1: use ct_in_net for parsed network membership. Hint 2: compare xx+yy <= 25. Expected device IDs 1 and 2; point IDs 1 and 2. Do not compare IPv6 strings lexicographically for network membership.
PostgreSQL 17 example — NOT RUN
SELECT inet '192.0.2.10' <<= cidr '192.0.2.0/24', point(3,4) <-> point(0,0);Expected result, not executed: [[true, 5.0]]