Re: How to reset a sequence so it will start with 1 again?

Поиск
Список
Период
Сортировка
От Michael Fuhr
Тема Re: How to reset a sequence so it will start with 1 again?
Дата
Msg-id 20060113083733.GA89304@winnie.fuhr.org
обсуждение исходный текст
Ответ на How to reset a sequence so it will start with 1 again?  (Nico Grubert <nicogrubert@gmail.com>)
Список pgsql-general
On Fri, Jan 13, 2006 at 09:02:17AM +0100, Nico Grubert wrote:
> After I truncated tblperson I supposed that the Id will start with 1
> again if I insert a new record into tblperson. I thought, truncating the
>  table tblperson will also reset its sequence "tblperson_id_seq"!? Am I
> wrong?

Yes, that's wrong.  Deleting from or truncating a table doesn't
modify any sequences.

> After that, I tried to set the sequence back to 1 since I cannot set the
> sequence to 0 using setval() (error: value 0 is out of bounds for
> sequence). Unfortunately, setting the sequence back to 1 will start with
> id = 2

Not if you use the three-argument form of setval() with the third
argument set to false or if you use ALTER SEQUENCE.

http://www.postgresql.org/docs/8.0/interactive/functions-sequence.html
http://www.postgresql.org/docs/8.0/interactive/sql-altersequence.html

test=> CREATE SEQUENCE foo;
CREATE SEQUENCE
test=> SELECT nextval('foo');
 nextval
---------
       1
(1 row)

test=> SELECT nextval('foo');
 nextval
---------
       2
(1 row)

test=> SELECT setval('foo', 1, false);
 setval
--------
      1
(1 row)

test=> SELECT nextval('foo');
 nextval
---------
       1
(1 row)

test=> ALTER SEQUENCE foo RESTART WITH 1;
ALTER SEQUENCE
test=> SELECT nextval('foo');
 nextval
---------
       1
(1 row)

--
Michael Fuhr

В списке pgsql-general по дате отправления:

Предыдущее
От: "H.J. Sanders"
Дата:
Сообщение: Plans for 8.2?
Следующее
От: Nico Grubert
Дата:
Сообщение: Re: How to reset a sequence so it will start with 1 again?