Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 729
stef Avatar asked Jan 05 '12 15:01

stef


People also ask

How do you alter a sequence?

Sequences objects are created by using the CREATE SEQUENCE statement. Sequences are integer values and can be of any data type that returns an integer. The data type cannot be changed by using the ALTER SEQUENCE statement. To change the data type, drop and create the sequence object.

How do I change the order of a column in PostgreSQL?

"Alter column position" in the PostgreSQL Wiki says: PostgreSQL currently defines column order based on the attnum column of the pg_attribute table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.

How do I use Currval in PostgreSQL?

currval(' sequence_name ') Returns the most recently returned value from nextval(' sequence_name '). This value is associated with a PostgreSQL session, and if the nextval() function has not yet been called in the connected session on the specified sequence sequence_name , there will be no "current" value returned.


2 Answers

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)

like image 133
NPE Avatar answered Sep 22 '22 19:09

NPE


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.

like image 20
Erwin Brandstetter Avatar answered Sep 20 '22 19:09

Erwin Brandstetter