I’ve got the following table structure for storing IPs (PostgreSQL 11.14):
CREATE TABLE ips (
ip INET
);
INSERT INTO ips VALUES ('10.0.0.4');
INSERT INTO ips VALUES ('10.0.0.0/24');
INSERT INTO ips VALUES ('10.1.0.0/23');
INSERT INTO ips VALUES ('10.1.0.0/27');
I need to know which network range is duplicate to find overlapping network entries.
2
Answers
We can use
SUBSTRING()
here along with a regex pattern:inet && inet → boolean
operator tells you if there’s an overlap.It’s commutative, so you can apply an exclusion constraint on that table to block incoming overlapping entries:
You can decide to handle the conflicts as they come, either by ignoring them or being selective:
Since
MERGE
has only recently been added to PostgreSQL 15, on earlier versions you can get away with a PL/pgSQL upsert.To detect already existing overlaps, you can use
inet <<= inet → boolean
instead, to avoid listing both addresses of each overlapping pair, as suggested by @a_horse_with_no_name.