Skip to content
Advertisement

Reset Postgres auto-increment value to 0

I’m having a table where I sometimes enter data in inline editors where I manually add the id value which is usually auto-incremented.

In a case where id 4 was auto generated using scripts and then id 5 & 6 were added inline, whenever I run a insert query the db tries to auto-increment the value 4. But the value 5 has been added to database by a user using an inline editor. In such a case I used a script as below

SELECT SETVAL('<tableName>_id_seq', (SELECT MAX(id) FROM <tableName>));

Then the auto increment value gets assigned to the maximum id value the database currently contains thereby auto-incrementing for the insert queries successfully.

The issue I’m facing is when ever I clear the database, is there a method to reset the auto-increment value to 0 or something so the next insert queries will begin inserting with a value of 1 to the id column?

Advertisement

Answer

Seems I’ve found a handy answer for my question

ALTER SEQUENCE <tableName>_id_seq RESTART;

Hope this helps

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement