Skip to content
Advertisement

Postgres: Add constraint if it doesn’t already exist

Does Postgres have any way to say ALTER TABLE foo ADD CONSTRAINT bar ... which will just ignore the command if the constraint already exists, so that it doesn’t raise an error?

Advertisement

Answer

This might help, although it may be a bit of a dirty hack:

Then call with:

Updated:

As per Webmut’s answer below suggesting:

That’s probably fine in your development database, or where you know you can shut out the apps that depend on this database for a maintenance window.

But if this is a lively mission critical 24×7 production environment you don’t really want to be dropping constraints willy nilly like this. Even for a few milliseconds there’s a short window where you’re no longer enforcing your constraint which may allow errant values to slip through. That may have unintended consequences leading to considerable business costs at some point down the road.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement