Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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; 
like image 479
Vinaya Nayak Avatar asked Jul 25 '18 13:07

Vinaya Nayak


People also ask

How do you remove a unique key from a column?

First you need to know the exact name of the INDEX (Unique key in this case) to delete or update it. INDEX names are usually same as column names. In case of more than one INDEX applied on a column, MySQL automatically suffixes numbering to the column names to create unique INDEX names.

How do I find unique constraints in PostgreSQL?

To find the name of a constraint in PostgreSQL, use the view pg_constraint in the pg_catalog schema. Join the view pg_catalog. pg_constraint with the view pg_class ( JOIN pg_class t ON t. oid = c.


1 Answers

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.

like image 115
Kveld Ulf Avatar answered Sep 20 '22 07:09

Kveld Ulf