Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if sequence exists in Postgres (plpgsql)

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!

like image 700
Ilia Choly Avatar asked Aug 10 '12 16:08

Ilia Choly


People also ask

How do I find the sequence number in PostgreSQL?

CREATE SEQUENCE creates a new sequence number generator. This involves creating and initializing a new special single-row table with the name name . The generator will be owned by the user issuing the command. If a schema name is given then the sequence is created in the specified schema.

What is Nextval in Postgres?

Function. Description. nextval ( regclass ) → bigint. Advances the sequence object to its next value and returns that value. This is done atomically: even if multiple sessions execute nextval concurrently, each will safely receive a distinct sequence value.


2 Answers

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; 
like image 118
rfusca Avatar answered Oct 05 '22 17:10

rfusca


The answer from @rfusca works if you're sure that the name could only be valid for a sequence (i.e., you're confident that it would not be use for an ordinary table, index, view, composite type, TOAST table, or foreign table), and you're not concerned about multiple schemas. In other words, it works for most common cases, but it's not entirely rigorous.

If you want to test whether a sequence by that name exists in a particular schema, this should work:

-- Clear the search path so that the regclass of the sequence -- will be schema-qualified. SET search_path = ''; -- Do your conditional code. IF EXISTS (SELECT * FROM pg_class              WHERE relkind = 'S'                AND oid::regclass::text = 'public.' || quote_ident(seq_name))   THEN     RAISE EXCEPTION 'sequence public.% already exists!', seq_name END IF; -- Restore the normal search path. RESET search_path; 
like image 29
kgrittn Avatar answered Oct 05 '22 16:10

kgrittn