Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way to add surrogate key to existing Oracle DB table

I have to modify an existing table in a Oracle 10g DB with a few thousand records to add a surrogate autonumber key. One way that comes to my mind is to

  1. Create a new sequence
  2. Create the id column, allowing null values
  3. Updating the id column with the sequence
  4. Alter table to add "not null" and "primary key" for the new id column

Is there an easier or more efficient way of doing this (or is there some reason why this wouldn't work)?

like image 507
simon Avatar asked Feb 18 '10 09:02

simon


1 Answers

I'd do it the following way:

  1. Create the id column, allowing null values

  2. Issue this query:

    UPDATE  mytable
    SET     id = rownum
    
  3. Alter table to add NOT NULL and PRIMARY KEY for the new id column

  4. Create the sequence, seeding it to MAX(id) + 1 and use it for the further inserts.

like image 185
Quassnoi Avatar answered Nov 11 '22 15:11

Quassnoi