Check if sequence exists in Postgres (plpgsql)

Viewed 35351

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!

6 Answers

I'm not sure about the actual intent why the presence of the sequence must be checked. An alternative if the goal is to check if a sequence exists before creating it, the IF NOT EXISTS condition in PostgreSQL can be used:

CREATE SEQUENCE IF NOT EXISTS 'name'

See https://www.postgresql.org/docs/9.5/static/sql-createsequence.html

Related