CREATE UNIQUE INDEX IF NOT EXISTS in postgreSQL

user3429578 picture user3429578 · Jul 10, 2014 · Viewed 24.6k times · Source

Plese I would like to do in PostgreSQL something like

CREATE UNIQUE INDEX IF NOT EXISTS

Any idea?

Answer

Torge picture Torge · Jan 11, 2016

You can check, if an index with a given name does exist by this statement.

If your index name is some_table_some_field_idx

SELECT count(*) > 0
FROM pg_class c
WHERE c.relname = 'some_table_some_field_idx' 
AND c.relkind = 'i';

Starting from Postgres 9.5 you can even use

CREATE INDEX IF NOT EXISTS