How to replace foreign reference in PostgreSQL? [closed]

Posted on

Question :

Suppose I have a foreign reference column which is pointing to an item A, how do I change it to item B? I would like to modify all records whose foreign reference column is A to B.

Answer :

Sample data,

CREATE TABLE foo ( a int UNIQUE, b int UNIQUE );
CREATE TABLE bar ( c int REFERENCES foo(a) );

Simple ALTER statement,

ALTER TABLE bar
  DROP CONSTRAINT bar_c_fkey,
  ADD FOREIGN KEY (c) REFERENCES foo(b);

And, that worked!

                Table "public.bar"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 c      | integer |           |          | 
Foreign-key constraints:
    "bar_c_fkey" FOREIGN KEY (c) REFERENCES foo(b)

Leave a Reply

Your email address will not be published. Required fields are marked *