Uniquely Append to Array on Conflict PostgreSQL
-
26-02-2021 - |
Question
I've got two columns in PostgreSQL, hostname and ip. Hostname is the primary key and ip is an array of IPs. I want to be able to insert IPs for a give hostname, on conflict I want to append to the array with the data I'm trying to insert and the output data should be unique.
e.g
hostname - ip
test.com {1.1.1.1,2.2.2.2}
Input
I attempt to insert...
test.com {1.1.1.1, 3.3.3.3, 4.4.4.4}
Output
test.com {1.1.1.1, 2.2.2.2 ,3.3.3.3, 4.4.4.4}
insert into auto_scope_pre_proc (hostname,ip) values ('test.com', '{10.10.10.10, 10.10.10.22}'::inet[])
on conflict (hostname) do update
SET ip = array_append(auto_scope_pre_proc.ip,ip);
Solution
The function array_append does not filter duplicates entries. Here is a possible solution:
drop table auto_scope_pre_proc;
DROP TABLE
create table auto_scope_pre_proc
(
hostname varchar(20) primary key,
ip inet[]
);
CREATE TABLE
insert into auto_scope_pre_proc (hostname,ip) values ('test.com', '{1.1.1.1, 2.2.2.2}'::inet[])
on conflict (hostname) do update
set ip = array( select distinct unnest(auto_scope_pre_proc.ip || excluded.ip));
INSERT 0 1
select * from auto_scope_pre_proc;
hostname | ip
----------+-------------------
test.com | {1.1.1.1,2.2.2.2}
(1 row)
insert into auto_scope_pre_proc (hostname,ip) values ('test.com', '{1.1.1.1, 3.3.3.3, 4.4.4.4}'::inet[])
on conflict (hostname) do update
set ip = array (select distinct unnest(auto_scope_pre_proc.ip || excluded.ip));
INSERT 0 1
select * from auto_scope_pre_proc;
hostname | ip
----------+-----------------------------------
test.com | {4.4.4.4,2.2.2.2,3.3.3.3,1.1.1.1}
(1 row)
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange