views:

34

answers:

1

I have a table with some datas. Is there a way to add a PK without erase the table ?

+3  A: 

Lets say you have a test1 table to which you want to add a id (surrogate) autoincremental PK:

   ALTER TABLE test1 ADD COLUMN id SERIAL;
   UPDATE test1 SET id = nextval(pg_get_serial_sequence('test1','id'));
   ALTER TABLE test1 ADD PRIMARY KEY (id);
leonbloy
UPDATE test1 SET id = DEFAULT; also works.
Frank Heikens