Reputation: 4511
Example schema: http://sqlfiddle.com/#!1/3d410
I've already got a table and I want to add a new, not valid foreign key to the table. What's the correct syntax for adding a NOT VALID foreign key?
CREATE TABLE junks (
id serial PRIMARY KEY,
name text
);
CREATE TABLE trunks (
id serial PRIMARY KEY,
name text
-- no fk
);
-- and the below does not work!
--ALTER TABLE trunks ADD junk serial REFERENCES junks(id) NOT VALID;
Upvotes: 1
Views: 5576
Reputation: 341
This works:
ALTER TABLE trunks ADD CONSTRAINT FK_junk_id
FOREIGN KEY (id)
REFERENCES junks(id)
NOT VALID
;
See, e.g.: http://www.postgresql.org/docs/devel/static/ddl-alter.html#AEN2758
Upvotes: 1
Reputation: 125524
You first add the column:
alter table trunks add column junk serial;
Then add the constraint to the table:
alter table trunks add constraint the_constraint_name
FOREIGN KEY (junk)
REFERENCES junks (id)
not valid;
Upvotes: 4