Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql sequences

When I delete all records from a Postgresql table and then try to reset the sequence to start a new record with number 1 when it is inserted, i get different results :

SELECT setval('tblname_id_seq', (SELECT COALESCE(MAX(id),1) FROM tblname));

This sets the current value of the sequence to 1, but the NEXT record (actually the first because there are no records yet) gets number 2!

And I can't set it to 0, because the minimum value in the sequence is 1!

When I use :

ALTER SEQUENCE tblname_id_seq RESTART WITH 1;

the first record that is inserted actually gets number 1 ! But the above code doesn't accept a SELECT as a value instead of 1.

I wish to reset the sequence to number 1 when there are no records, and the first record then should start with 1. But when there ARE already records in the table, I want to reset the sequence so that the next record that is inserted will get {highest}+1

Does anyone have a clear solution for this?

like image 458
Dylan Avatar asked Jan 12 '11 02:01

Dylan


2 Answers

Use the three-argument form of setval to set the is_called flag to false, so that it returns the current value of the sequence for the next nextval call rather than immediately generating a new one.

http://www.postgresql.org/docs/current/interactive/functions-sequence.html

Also note you need to use COALESCE(MAX(id),0)+1, otherwise the first value from the sequence will be MAX(id), which you know to already exist. (thx Stephen Denne)

like image 115
araqnid Avatar answered Sep 22 '22 10:09

araqnid


See http://www.postgresql.org/docs/current/static/functions-sequence.html, near the bottom of the page.

Specifically, at least in Postgresql 9.0, you can find and set the value of a sequence. You can use the three-argument form of setval() to set either the current value of the sequence or the next value of the sequence (which would allow you to set the sequence to 1 on the next value retrieval).

like image 26
Andrew Avatar answered Sep 21 '22 10:09

Andrew