Retrospectivly adding a unique primary id column to a table in postgresql

I had created a table in PostgreSQL, but I hadn't added an primary key or unique id field. This StackOverflow question explains how to add an auto-increment field when you're creating the table, but that doesn't work if you have already created the table. I didn't want to recreate the table, since it was relatively big.

It is possible to add a unique field after the fact with this sequence of SQL. This assumes your table is called mytable and that you want there to be an id field as primary key:

CREATE SEQUENCE my_ids;
ALTER TABLE mytable ADD id INT UNIQUE;
UPDATE mytable SET id = NEXTVAL('my_ids');

Source

Comments !

blogroll