Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset auto increment counter in postgres

I would like to force the auto increment field of a table to some value, I tried with this:

ALTER TABLE product AUTO_INCREMENT = 1453 

AND

ALTER SEQUENCE product  RESTART WITH 1453; ERROR:  relation "your_sequence_name" does not exist 

I'm new to postgres :(

I have a table product with Id and name field

like image 796
Rad Avatar asked Mar 17 '11 16:03

Rad


People also ask

How do I reset auto increment counter?

In MySQL, the syntax to reset the AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = value; table_name. The name of the table whose AUTO_INCREMENT column you wish to reset.

Is there auto increment in PostgreSQL?

PostgreSQL has the data types smallserial, serial and bigserial; these are not true types, but merely a notational convenience for creating unique identifier columns. These are similar to AUTO_INCREMENT property supported by some other databases.

Is primary key auto increment by default in PostgreSQL?

By simply setting our id column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our id column with a unique, primary key value for every INSERT .


2 Answers

If you created the table product with an id column, then the sequence is not simply called product, but rather product_id_seq (that is, ${table}_${column}_seq).

This is the ALTER SEQUENCE command you need:

ALTER SEQUENCE product_id_seq RESTART WITH 1453 

You can see the sequences in your database using the \ds command in psql. If you do \d product and look at the default constraint for your column, the nextval(...) call will specify the sequence name too.

like image 111
araqnid Avatar answered Oct 06 '22 06:10

araqnid


The following command does this automatically for you: This will also delete all the data in the table. So be careful.

TRUNCATE TABLE someTable RESTART IDENTITY; 
like image 37
Loolooii Avatar answered Oct 06 '22 06:10

Loolooii