1

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;
1
  • 1
    So what's wrong with the NOT VALID option you found yourself? Commented Dec 20, 2012 at 12:56

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

How to alter an already added and valid constraint?
1

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

Comments

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.