user880386 user880386 - 2 months ago 21
SQL Question

How to drop constraints in postgres?

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 I can write this query in postgres?
Thanks in advance

Answer

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;
Comments