5

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?

1
  • 2
    This is not possible. Normalise the schema and use a separate table. Commented Aug 6, 2020 at 2:00

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
basically a variation of stackoverflow.com/questions/8016776/… but uniqueness is Per array in each Row and not throughout the table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.