Oracle SQL - Add Primary Key to table

Dimitri Dewaele picture Dimitri Dewaele · Nov 6, 2013 · Viewed 72.5k times · Source

I have some columns with no primary key and want to add a primary key column.

NAME    Age
-------------
Peter   45
Bob     25
John    56
Peter   45

Some collegues suggest to add a PK with a sequences and triggers: Add a auto increment primary key to existing table in oracle

This is nice, but my customers use a Database User with no rights to add sequences or triggers. I want to prevent to contact dozens of DBA administrators to alter user rights or to run my scripts.

This is my suggestion to add a PK with only an update statement: (I need help in Step 2)

Step 1: Create the ID column (I have DB rights for this)

ALTER TABLE PERSON ADD ID NUMBER(10,0);

Step 2: Question: Can I initialize the ID column with unique values based on the order of the rows or something else? How?

UPDATE PERSON SET ID = something-unique

Step 3: Add the primary key contraint afterwords: (I DB have rights for this)

ALTER TABLE PERSON ADD CONSTRAINT PK_ID PRIMARY KEY(ID);

Step 4: Afterwords: the primary key is managed and added by my application.

This will be the result:

ID(PK)  NAME    Age
---------------------
1       Peter   45
2       Bob     25
3       John    56
4       Peter   45

Thanks folks!

Answer

WW. picture WW. · Nov 6, 2013
Update person set id = rownum;