Need to check each element of an array satisfies a foreign key constraint

From: David Gauthier <davegauthierpg(at)gmail(dot)com>
To: Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Need to check each element of an array satisfies a foreign key constraint
Date: 2021-07-13 14:00:34
Message-ID: CAMBRECBOOybGgVKHe_E6MYqY7VJ-rS4YME8SwpK5+baAg3cRgg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi:

I have a column in a table which is a csv of values and I need to make sure
each element of the csv = the PK of that same table.

create table projects (
project varchar primary key,
children_csv varchar );

insert into projects (project,children_csv) values
('prj1',null),
('prj2',null),
('prj3','prj1,prj2');

I need to make sure that the elements of 'prj1,prj2' are both valid
projects.

I'm thinking the csv should be split into an array (regexp_split_to_array)
but the constraint needs to somehow iterate over each element to check that
they are all valid.

I suppose I could write a stored procedure to do this and call it in a
check constraint. But I was wondering if there is something more elegant.

Thanks in Advance !

Responses

Browse pgsql-general by date

  From Date Subject
Next Message David G. Johnston 2021-07-13 14:07:57 Re: Need to check each element of an array satisfies a foreign key constraint
Previous Message Peter Eisentraut 2021-07-13 13:43:12 Re: pg_wal lifecycle