How to drop a unique constraint on a column in Postgres?

Vinaya Nayak picture Vinaya Nayak · Jul 25, 2018 · Viewed 13.6k times · Source

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;

Answer

Kveld Ulf picture Kveld Ulf · Jul 25, 2018

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.