Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset sequence value as 1

Tags:

postgresql

I need that after TRUNCATE table, reset his sequence, for this I do :

SELECT setval('mytable_id_seq', 1) 

After, when insert rows in table, sequence is started from 2 not 1

How to resert sequence value such, that new first value will be 1?

 SELECT setval('mytable_id_seq', 0) // gives error that value is out of range
like image 670
Oto Shavadze Avatar asked May 10 '13 15:05

Oto Shavadze


2 Answers

First set the minimum value of the sequence

alter sequence mytable_id_seq minvalue 0 start with 1;

Now either reset it:

SELECT setval('mytable_id_seq', 0)

Or reset it while truncating:

truncate mytable restart identity;
like image 160
Clodoaldo Neto Avatar answered Oct 11 '22 12:10

Clodoaldo Neto


Either use the third argument for setval():

setval(yourseq, 1, false)

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

Or alter the sequence:

alter sequence yourseq restart

http://www.postgresql.org/docs/current/static/sql-altersequence.html

like image 26
Denis de Bernardy Avatar answered Oct 11 '22 13:10

Denis de Bernardy