Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL - Add Primary Key to table

Tags:

sql

key

add

oracle

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!

like image 411
Dimitri Dewaele Avatar asked Nov 06 '13 08:11

Dimitri Dewaele


People also ask

Can I add primary key to existing table?

Because a table can have only one primary key, you cannot add a primary key to a table that already has a primary key defined. To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key.

Can primary key be updated in Oracle?

Yes, there is a way to do the cascading update in Oracle, even within a transaction (which does not hold true for the option of enabling/disabling constraints). However, you'll have to implement it yourself. It can be done via before/after-row-update triggers.


1 Answers

Update person set id = rownum;
like image 193
WW. Avatar answered Oct 06 '22 01:10

WW.