Last Updated: February 25, 2016
·
1.098K
· cathywise

Postgres: Add Sequential PKEY

So you forgot to add a primary key? Or you did have one, but now that field isn't going to be unique? Fear not.

alter table sad_table drop constraint if exists sad_table_pkey;
alter table sad_table add column id int;
create sequence sad_table_id_seq;
alter table sad_table alter column id set default nextval('sad_table_id_seq');
update sad_table set id = nextval('sad_table_id_seq');
alter table sad_table add primary key (id);

I won't tell.