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

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Nico Grubert <nicogrubert(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: How to reset a sequence so it will start with 1 again?
Date: 2006-01-13 08:37:33
Message-ID: 20060113083733.GA89304@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Nico Grubert 2006-01-13 08:38:11 Re: How to reset a sequence so it will start with 1 again?
Previous Message H.J. Sanders 2006-01-13 08:30:22 Plans for 8.2?