Postgres manually alter sequence

前端 未结 5 1518
盖世英雄少女心
盖世英雄少女心 2020-11-28 18:56

I\'m trying to set a sequence to a specific value.

SELECT setval(\'payments_id_seq\'), 21, true

This gives an error:

5条回答
  •  有刺的猬
    2020-11-28 18:56

    This syntax isn't valid in any version of PostgreSQL:

    ALTER SEQUENCE payments_id_seq LASTVALUE 22

    This would work:

    ALTER SEQUENCE payments_id_seq RESTART WITH 22;
    

    and is equivalent to:

    SELECT setval('payments_id_seq', 22, FALSE);
    

    More in the current manual for ALTER SEQUENCE and sequence functions.

    Note that setval() expects either (regclass, bigint) or (regclass, bigint, boolean). In the above example I am providing untyped literals. That works too. But if you feed typed variables to the function you may need explicit type casts to satisfy function type resolution. Like:

    SELECT setval(my_text_variable::regclass, my_other_variable::bigint, FALSE);
    

    For repeated operations you might be interested in:

    ALTER SEQUENCE payments_id_seq START WITH 22; -- set default
    ALTER SEQUENCE payments_id_seq RESTART;       -- without value
    

    START [WITH] stores a default RESTART number, which is used for subsequent RESTART calls without value. You need Postgres 8.4 or later for the last part.

提交回复
热议问题