Check if sequence exists in Postgres (plpgsql)

Ilia Choly picture Ilia Choly · Aug 10, 2012 · Viewed 29.6k times · Source

I'm trying to test, within a stored procedure, whether a sequence already exists.

IF EXISTS SEQUENCE seq_name
    RAISE EXCEPTION 'sequence % already exists!', seq_name
END IF;

I have tried several variations of the snippet above without luck. I must be giving Google the wrong terms because I can't seem to find anything on the topic. Any help is appreciated!

Answer

rfusca picture rfusca · Aug 10, 2012

You should be able query the pg_class table to see if the relname exists.

IF EXISTS (SELECT 0 FROM pg_class where relname = '<my sequence name here>' )
THEN
  --stuff here
END IF;