user1888543
user1888543

Reputation: 391

How to add a sequence column to an existing table with records

I had created a new table named USERLOG with two fields from a previous VIEW. The table already consist of about 9000 records. The two fields taken from the VIEW, i.e. weblog_views consist of IP (consists of IP address), and WEB_LINK (consists of URL). This is the code I used,

    CREATE TABLE USERLOG
    AS
    SELECT C_IP, WEB_LINK FROM weblog_views;

I want to add another column to this table called the USER_ID, which would consists of a sequence starting with 1 to 9000 records to create a unique id for each existing rows. I need help with this part. I'm using Oracle SQL Developer: ODMiner version 3.0.04. I tried using the AUTO-INCREMENT option,

    ALTER TABLE USERLOG
    ADD USER_ID INT UNSIGNED NOT NULL AUTO_INCREMENT;

But I get an error with this,

    Error report:
    SQL Error: ORA-01735: invalid ALTER TABLE option
    01735. 00000 -  "invalid ALTER TABLE option"

So, I would really appreciate any help that I can get!

Upvotes: 31

Views: 142272

Answers (3)

Madhulik Arya
Madhulik Arya

Reputation: 41

Step 1. Create sequence to be used by the column eg:

CREATE SEQUENCE user_id_seq
  START WITH 1
  INCREMENT BY 1
  CACHE 20;

Step 2. Update new column with sequence eg:

UPDATE userlog
   SET user_id = user_id_seq.nextval;

Step 3. - Set Sequence as the default value for the column, will work only above Oracle 12c

ALTER TABLE USERLOG
    MODIFY USER_ID INT DEFAULT user_id_seq.nextval;

Upvotes: 4

fuggi
fuggi

Reputation: 331

In addition to Justin's excellent answer you might want to prevent NULL values for your user_id in the future (as they could still be caused by UPDATE statements). Therefore, execute the following statement at the end:

ALTER TABLE userlog MODIFY(user_id number NOT NULL);

Upvotes: 1

Justin Cave
Justin Cave

Reputation: 231661

You would need to add a column

ALTER TABLE userlog
  ADD( user_id number );

create a sequence

CREATE SEQUENCE user_id_seq
  START WITH 1
  INCREMENT BY 1
  CACHE 20;

Update the data in the table

UPDATE userlog
   SET user_id = user_id_seq.nextval

Assuming that you want user_id to be the primary key, you would then add the primary key constraint

ALTER TABLE userlog
  ADD CONSTRAINT pk_user_id PRIMARY KEY( user_id );

If you want to use the sequence to automatically add the user_id when you do an INSERT (the other option would be to specifically reference user_id_seq.nextval in your INSERT statements, you would also need a trigger

CREATE OR REPLACE TRIGGER trg_userlog_user_id
  BEFORE INSERT ON userlog
  FOR EACH ROW
BEGIN
  :new.user_id := user_id_seq.nextval;
END;

Upvotes: 62

Related Questions