Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

I have a table with existing data. Is there a way to add a primary key without deleting and re-creating the table?

like image 904
xRobot Avatar asked May 31 '10 15:05

xRobot


People also ask

Does Postgres auto-increment primary key?

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 .

How do I add an auto-increment to an existing table?

To add a new AUTO_INCREMENT integer column named c : ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (c); We indexed c (as a PRIMARY KEY ) because AUTO_INCREMENT columns must be indexed, and we declare c as NOT NULL because primary key columns cannot be NULL .

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.

How do I add a primary key constraint to an existing table in PostgreSQL?

In PostgreSQL, a primary key is created using either a CREATE TABLE statement or an ALTER TABLE statement. You use the ALTER TABLE statement in PostgreSQL to add or drop a primary key.


2 Answers

(Updated - Thanks to the people who commented)

Modern Versions of PostgreSQL

Suppose you have a table named test1, to which you want to add an auto-incrementing, primary-key id (surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:

   ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY; 

Older Versions of PostgreSQL

In old versions of PostgreSQL (prior to 8.x?) you had to do all the dirty work. The following sequence of commands should do the trick:

  ALTER TABLE test1 ADD COLUMN id INTEGER;   CREATE SEQUENCE test_id_seq OWNED BY test1.id;   ALTER TABLE test ALTER COLUMN id SET DEFAULT nextval('test_id_seq');   UPDATE test1 SET id = nextval('test_id_seq'); 

Again, in recent versions of Postgres this is roughly equivalent to the single command above.

like image 126
6 revs, 2 users 85% Avatar answered Sep 27 '22 18:09

6 revs, 2 users 85%


ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY; 

This is all you need to:

  1. Add the id column
  2. Populate it with a sequence from 1 to count(*).
  3. Set it as primary key / not null.

Credit is given to @resnyanskiy who gave this answer in a comment.

like image 45
Synesso Avatar answered Sep 27 '22 18:09

Synesso