6

I have a small problem with adding new CONSTRAINT to my table.
I want to add a UNIQUE CONSTRAINT and do not validate existing data in my table.

I have some duplicates in existing data and I want to leave it like it is.

I wrote a query:

ALTER TABLE tbl1 
   ADD CONSTRAINT unique_const UNIQUE (fld1, fld2) NOT VALID;

But it's not working, I got an error:

UNIQUE constraints cannot be marked NOT VALID

I also tried removing all TRIGGERS:

ALTER TABLE tbl1 DISABLE TRIGGER all;
ALTER TABLE tbl1 ADD CONSTRAINT unique_const UNIQUE (fld1, fld2);
ALTER TABLE tbl1 ENABLE TRIGGER all;

But it also does not work.

Does anyone know how to add a UNIQUE CONSTRAINT without validating existing rows?

2 Answers 2

2

According to the documentation of PostgreSQL 9.6, unfortunately the NOT VALID option is currently only allowed with foreign key and CHECK constraints. This StackOverflow thread here might be related and provide ideas/basic approaches for an alternative solution, although it's from 2014.

Sign up to request clarification or add additional context in comments.

3 Comments

This is also true for 9.5 and 9.6
Thank you very much. Edited that. :)
Thanks, this was useful to me too! I used NOT VALID to add back a foreign key constraint after I loaded some data that contained some records that would violate this constraint.
2

If you can specifically identify those lines which should be ignored for the constraint, you could add a partial unique index:

CREATE UNIQUE INDEX ON table (columns) WHERE some_condition;

If you don't have an existing direct condition, you may need to add a column to the table to identify those lines that should be ignored (with an appropriate default so that new lines are counted).

Not sure if there's an equivalent ALTER TABLE syntax.

1 Comment

is it ok if we leave the old data without intention to correct it? so we never remove the condition from our index

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.