Re: How to reset a sequence so it will start with 1 again? - Mailing list pgsql-general

From Michael Fuhr
Subject Re: How to reset a sequence so it will start with 1 again?
Date
Msg-id 20060113083733.GA89304@winnie.fuhr.org
Whole thread Raw
In response to How to reset a sequence so it will start with 1 again?  (Nico Grubert <nicogrubert@gmail.com>)
List 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 by date:

Previous
From: "H.J. Sanders"
Date:
Subject: Plans for 8.2?
Next
From: Nico Grubert
Date:
Subject: Re: How to reset a sequence so it will start with 1 again?