IF NOT EXISTS
/IF EXISTS
Many commands do offer a IF NOT EXISTS
clause.
You found that in the CREATE TABLE
command.
Adding/dropping a column do too, in Postgres. See documentation.
ADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ]
DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ]
Drop, then add
Some commands do not support IF NOT EXISTS
. One of those is adding a constraint. This Answer suggests executing a DROP CONSTRAINT IF EXISTS
before doing ADD CONSTRAINT
. This drop-then-add approach may work in some other situations as well.
That other Question also has other Answers with various approaches you may want to consider.
But I expect that for more complicated scenarios, you may need to track whether SQL operations have already been performed.
Flyway for the win
Flyway, Liquibase, etc. really are the best solution for tracking which SQL scripts have been run and which need to be run.
Otherwise you will need to devise a way to track which scripts have been run. I would rather rely on a solution already built & tested.