Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop constraints in postgres?

Tags:

sql

postgresql

I have this query in SQL:

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id('[FK_states_list]') AND OBJECTPROPERTY(id, 'IsForeignKey') = 1) ALTER TABLE [custom_table] DROP CONSTRAINT [FK_states_list] ; 

How can I write this query in Postgres?

like image 291
user880386 Avatar asked Sep 15 '16 13:09

user880386


People also ask

Can we drop a constraints?

To drop an existing constraint, specify the DROP CONSTRAINT keywords and the identifier of the constraint. To drop multiple constraints on the same table, the constraint names must be in comma-separated list that is delimited by parentheses. The constraint that you drop can have an ENABLED, DISABLED, or FILTERING mode.

How do I change unique constraints in PostgreSQL?

The syntax for creating a unique constraint The below illustrations are used to create a Unique constraint with the ALTER TABLE command in PostgreSQL: ALTER TABLE table_name. ADD CONSTRAINT [ constraint_name ] UNIQUE(column_list);


1 Answers

It seems you want to drop the constraint, only if it exists.

In Postgres you can use:

ALTER TABLE custom_table    DROP CONSTRAINT IF EXISTS fk_states_list; 

You can also make sure the table exists:

ALTER TABLE IF EXISTS custom_table    DROP CONSTRAINT IF EXISTS fk_states_list; 
like image 168
a_horse_with_no_name Avatar answered Sep 22 '22 11:09

a_horse_with_no_name