Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the starting value of a serial - Postgresql

Tags:

postgresql

I've a little problem with serial : From a file, I filled my database in which I have a client ID (it is a serial and it is my primary key). I have 300 clients so 300 client ID (1 to 300). Now my problem is, I've a form for new clients.I cannot add them because when I add a client, my program adds the client with ID 1 or the ID 1 is already assigned to another client.

So my question is : is it possible to change the starting value of a serial for to resolve this problem ?

like image 984
afk Avatar asked May 03 '13 15:05

afk


People also ask

Can we update primary key in PostgreSQL?

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.

What is the difference between serial and sequence in PostgreSQL?

There is essentially no difference.

How do I change the order of a column in PostgreSQL?

Postgres currently defines column order based on the attnum column of the pg_attribute table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.


2 Answers

You can alter a sequence using RESTART WITH to change the current sequence number;

ALTER SEQUENCE test_seq RESTART WITH 300; 

To get the sequence name if you created it using the serial keyword, use

SELECT adsrc FROM pg_attrdef WHERE adrelid = (SELECT oid FROM pg_class WHERE relname = 'table name goes here');  

An SQLfiddle to test with.

like image 77
Joachim Isaksson Avatar answered Oct 30 '22 01:10

Joachim Isaksson


PostgreSQL

ALTER SEQUENCE tablename_columnname_seq RESTART WITH anynumber; 

Example:

ALTER SEQUENCE test_table_rec_id_seq RESTART WITH 4615793; 
like image 35
Karthik Mayya Avatar answered Oct 30 '22 00:10

Karthik Mayya