I’m working with PostgreSQL and have a script that attempts to create a sequence named hibernate_seq and set its starting value:
CREATE SEQUENCE IF NOT EXISTS hibernate_seq;
SELECT setval('hibernate_seq', (SELECT MAX(NEXT_HI) + 1 FROM HIBERNATE_ID_GENERATION));
However, I want to achieve the following behavior:
Create the sequence hibernate_seq only if it doesn’t already exist.
Set the sequence’s starting value but only if the sequence is newly created.
In other words, if the sequence hibernate_seq already exists, I don’t want to accidentally modify its current value.
how can I do that?
2
Answers
Something like:
This uses an anonymous function(DO) and
FOUND
from here Result status to test whether the sequence already exists and if it does not the creates the sequence and sets the value. Otherwise leaves the sequence aloneA safe version that covers most possible hickups – and attaches the new sequence properly to make it a
serial
column.See:
How to reset Postgres' primary key sequence when it falls out of sync?
Get table and column "owning" a sequence
Show only list of tables without child partitions
Creating a PostgreSQL sequence to a field (which is not the ID of the record)