Postgres manually alter sequence
I'm trying to set a sequence to a specific value.
SELECT setval('payments_id_seq'), 21, true
This gives an error:
ERROR: function setval(unknown) does not exist
Using ALTER SEQUENCE
doesn't seem to work either?
ALTER SEQUENCE payments_id_seq LASTVALUE 22
How can this be done?
Ref: https://www.postgresql.org/docs/current/static/functions-sequence.html
Solution 1:
The parentheses are misplaced:
SELECT setval('payments_id_seq', 21, true); # next value will be 22
Otherwise you're calling setval
with a single argument, while it requires two or three.
This is the same as SELECT setval('payments_id_seq', 21)
Solution 2:
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.