Search code examples
arrayspostgresqlconstraintspostgresql-12postgresql-13

How to add Foreign key constraint on array in PostgreSQL?


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?


Solution

  • 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.