Reset sequence value as 1

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

 SELECT setval('mytable_id_seq', 1) 

After inserting rows into a table, the sequence begins with 2 not 1

How to save a sequence value such that the new first value will be 1 ?

  SELECT setval('mytable_id_seq', 0) // gives error that value is out of range 
+4
source share
2 answers

First set the minimum sequence value

 alter sequence mytable_id_seq minvalue 0 start with 1; 

Now either reset it:

 SELECT setval('mytable_id_seq', 0) 

Or reset when truncating:

 truncate mytable restart identity; 
+9
source

Use the third argument to setval() :

setval(yourseq, 1, false)

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

Or change the sequence:

 alter sequence yourseq restart 

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

+4
source

Source: https://habr.com/ru/post/1480136/


All Articles