Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing primary key int type to serial

Is there a way to change existing primary key type from int to serial without dropping the table? I already have a lot of data in the table and I don't want to delete it.

like image 652
MarisP Avatar asked May 10 '14 07:05

MarisP


People also ask

How do I change the datatype in PostgreSQL?

First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.

What does the serial keyword do and when do you use it?

The SERIAL data type stores a sequential integer, of the INT data type, that is automatically assigned by the database server when a new row is inserted. The default serial starting number is 1, but you can assign an initial value, n, when you create or alter the table.

What is auto increment in PostgreSQL?

Advertisements. 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.


1 Answers

Converting an int to a serial more or less only means adding a sequence default to the value, so to make it a serial;

  • Pick a starting value for the serial, greater than any existing value in the table
    SELECT MAX(id)+1 FROM mytable

  • Create a sequence for the serial (tablename_columnname_seq is a good name)
    CREATE SEQUENCE test_id_seq MINVALUE 3 (assuming you want to start at 3)

  • Alter the default of the column to use the sequence
    ALTER TABLE test ALTER id SET DEFAULT nextval('test_id_seq')

  • Alter the sequence to be owned by the table/column;
    ALTER SEQUENCE test_id_seq OWNED BY test.id

A very simple SQLfiddle demo.

And as always, make a habit of running a full backup before running altering SQL queries from random people on the Internet ;-)

like image 182
Joachim Isaksson Avatar answered Sep 19 '22 20:09

Joachim Isaksson