2

How to add Foreign key constraint on array in PostgreSQL?

look_up table for roles

CREATE TABLE party_role_cd
(
  party_role_cd bigint NOT NULL,
  code character varying(80) NOT NULL,
  CONSTRAINT party_role_cd PRIMARY KEY (party_role_cd)
);

Party can have zero or many roles [ 0-N relationship ]

CREATE TABLE party
(
  party_id biging NOT NULL,
  party_role_cd bigint[] NOT NULL,
  CONSTRAINT party_id PRIMARY KEY (party_id)
);

How to add the foreign key constraint for party_role_cd array in party table?

Thirumal
  • 8,280
  • 11
  • 53
  • 103

1 Answers1

4

That's not implemented in PostgreSQL. Currently, FK constraints only operate on equality between whole column values. No array-to-element references. There is an open TODO item that has been added in 2010. See:

There were even attempts to implement it, but never to completion.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • i had a similar Problem. I am thinking if I have a table: `id (serial), array(Integers[])` then I Will have a seperate table: `id_of_table1, array_element (Integer)` Table 1 & table 2 are always in sync through insert/update/delete Triggers. Now array_element is a foreign key of another table. In addition I need to make sure each array has unique elements.. I can achieve that by Unique Index on `id_of_table1, array_element` – Cpp crusaders May 06 '22 at 11:25
  • basically a variation of https://stackoverflow.com/questions/8016776/can-postgresql-have-a-uniqueness-constraint-on-array-elements/8017013#8017013 but uniqueness is Per array in each Row and not throughout the table – Cpp crusaders May 06 '22 at 11:52