Reset Postgres auto-increment value to 0

Viewed 1723

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?

3 Answers

Seems I've found a handy answer for my question

ALTER SEQUENCE <tableName>_id_seq RESTART;

Hope this helps

Here is an example of what i do i my sql to restart the index from my database. I use this code when resetting the entities for unit testing my api.

In my database i have a table terminal:

CREATE TABLE IF NOT EXISTS terminal(
    id SERIAL PRIMARY KEY,
    "serialNumber" VARCHAR(255),
    "storeCode" VARCHAR(100),
    "modelCode" VARCHAR(31)
);

It will create a table with a primary key terminal_id_seq.

ALTER SEQUENCE terminal_id_seq RESTART WITH 1;
DELETE FROM terminal;
--redo the inserts
INSERT INTO terminal ("id", "serialNumber", "storeCode","modelCode") VALUES (10,'abc','def','blabla');

Hope it helps.

There are a number of ways to do this as outlined above, but if you want a more idempotent way to do it (which you do), then I'd recommend:

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

This way you can use the same code whether you have rows in the table or not, and it will do the right thing.

Related