Search code examples
sqlpostgresqlddl

Postgresql: DROP CONSTRAINT IF EXISTS not working


I want to delete a constraint only if it exists. But it's not working or I do something wrong.

Here is my query:

IF EXISTS (SELECT * FROM information_schema.table_constraints WHERE constraint_name='res_partner_bank_unique_number')
THEN ALTER TABLE res_partner_bank DROP CONSTRAINT res_partner_bank_unique_number;

It gives me this error:

ERROR: syntax error at or near "IF"

If anybody can help me please. Thanks.

Regards.


Solution

  • There is no IFin SQL (only in PL/pgSQL).

    But drop constraint supports the IF NOT EXISTS option:

    ALTER TABLE res_partner_bank 
      DROP CONSTRAINT IF EXISTS res_partner_bank_unique_number;