40

This is my database table

CREATE TABLE cart (
  id           UUID      NOT NULL PRIMARY KEY,
  shop_user_id UUID UNIQUE
);

And when I try to delete the UNIQUE constraint on shop_user_id I get the sql 42601 error

This is the query I use to delete the unique constraint

ALTER TABLE cart DROP UNIQUE shop_user_id;
0

2 Answers 2

74

To find the name of the unique constraint, run

SELECT conname
FROM pg_constraint
WHERE conrelid = 'cart'::regclass
  AND contype = 'u';

Then drop the constraint as follows:

ALTER TABLE cart DROP CONSTRAINT cart_shop_user_id_key;

Replace cart_shop_user_id_key with whatever you got from the first query.

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

3 Comments

select * from information_schema.table_constraints; Find the constraint. Make sure to drop it from the table, then drop the unique value.
I ran select * from information_schema.table_constraints; This still shows the constraint name in there. But the problem is how to drop it?
Does not work always: select * from pg_indexes where indexname = 'train_on_track_history_unique'; returns index train_on_track_history_unique for table train_on_track_history, schema edr # alter table edr.train_on_track_history drop constraint train_on_track_history_unique; constraint "train_on_track_history_unique" of relation "train_on_track_history" does not exist #drop index train_on_track_history_unique; does not exist
5

For example:

    CREATE TABLE teachers( teacher_id SERIAL PRIMARY KEY,
email VARCHAR(250) UNIQUE NOT NULL);


select * from information_schema.table_constraints;

ALTER TABLE teachers DROP CONSTRAINT teachers_email_key;

1 Comment

I like this answer as an addendum to the accepted answer, since the table_constraints view provides a much more human readable result.

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.