user3079679
user3079679

Reputation: 35

How do you update a column to a foreign key?

Here is the table I created:

CREATE TABLE enrolled
(
  sid integer NOT NULL,
  ccode character varying(6) NOT NULL,
  CONSTRAINT enrolled_pkey1 PRIMARY KEY (sid, ccode)
);

Now I want to UPDATE the ccode column to be declared as a foreign key from a table called Class. How do I do that?

Upvotes: 2

Views: 86

Answers (1)

Maciej Sz
Maciej Sz

Reputation: 12035

ALTER TABLE ONLY enrolled
    ADD CONSTRAINT enrolled_ccode_fkey FOREIGN KEY (ccode)
        REFERENCES class(ccode)
    ON UPDATE CASCADE ON DELETE RESTRICT;

But for this to work remember, that you must have a unique index on the class.ccode column:

CREATE UNIQUE INDEX class_ccode_idx ON class USING btree (ccode);

Upvotes: 1

Related Questions