Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset PostgreSQL primary key to 1

Is there a way to reset the primary key of a PostgreSQL table to start at 1 again on a populated table?

Right now it's generating numbers from 1000000 and up. I want it all to reset and start to 1, keeping all my existing data intact.

like image 702
David Avatar asked Sep 29 '10 06:09

David


People also ask

How do I reset my primary key to 1?

alter table yourTableName AUTO_INCREMENT=1; truncate table yourTableName; After doing the above two steps, you will get the primary key beginning from 1.

How do I change the primary key in a table Postgres?

To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key. Note You must be logged in to the database using a database name before you can add a primary key or conduct any other referential integrity (RI) operation.

Does truncate reset auto increment in Postgres?

Sometimes that data is in a table with an auto-incrementing ID and I use the TRUNCATE command to remove all data and reset the auto-increment value to 0 for a given table.


4 Answers

The best way to reset a sequence to start back with number 1 is to execute the following:

ALTER SEQUENCE <tablename>_<id>_seq RESTART WITH 1

So, for example for the users table it would be:

ALTER SEQUENCE users_id_seq RESTART WITH 1
like image 95
Paweł Gościcki Avatar answered Oct 05 '22 06:10

Paweł Gościcki


See a better option here: https://stackoverflow.com/a/5272164/5190

Primary keys that autoincrement (i.e., columns with data type serial primary key) are associated with a sequence. You can set the next value for any sequence using the setval(<seqname>, <next_value>) function. Note that to actually execute the function by itself you need to use SELECT, like this: SELECT setval(<seqname>, <next_value>)

The name of the auto created sequences when using serial are <table>_<column>_seq

like image 37
Vinko Vrsalovic Avatar answered Oct 05 '22 06:10

Vinko Vrsalovic


TRUNCATE TABLE table_name RESTART IDENTITY;

This will delete all of your data. Maybe some users looking for something like this as I am.

like image 35
ZootHii Avatar answered Oct 05 '22 05:10

ZootHii


@bluish actually inserting a new record using an auto-incremented primary key, is just like using a sequence explicitly this way:

INSERT INTO MyTable (id, col1, ...) VALUES (MySeq.nextval(), val1, ...)

So, if you want the first id to be 1, you should have to set your sequence to 0. But it's out of bounds, so you must use the ALTER SEQUECE statement. So, if you have a serial field named number in your table menu, for exemple:

ALTER SEQUENCE menu_number_seq RESTART

will make the job perfectly.

like image 22
ROQUEFORT François Avatar answered Oct 05 '22 06:10

ROQUEFORT François