Search code examples
postgresqlddldatabase-sequence

How to create script with Postgresql to parameterize the start value of a sequence


I'm newbie in Postgres. I use Pgadmin III and I need to parameterize a value in a statament of 'alter sequence'. I have tried to execute this code:

select coalesce(MAX(ID)+1,1) as max into myTempTable from myTable;
EXECUTE immediate 'ALTER SEQUENCE mySequence INCREMENT BY 1 START WITH ' || max || ' MINVALUE 1 NO CYCLE';

but it doesn't work. What's wrong? I need to encapsulate it in a function? Thank you. D.


Solution

  • For setting value to sequence manually, you can use ALTER SEQUENCE seq_name RESTART WITH value

    Regarding to your example, you need something like this:

    CREATE SEQUENCE testseq;
    
    DO $$
    DECLARE
        maxid INT;
    BEGIN
        SELECT coalesce(MAX(ID)+1,1) FROM myTable INTO maxid;
        EXECUTE 'ALTER SEQUENCE testseq RESTART WITH '|| maxid;
    END;
    $$ LANGUAGE PLPGSQL