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!
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.
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.
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With