Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle - Modify an existing table to auto-increment a column

I have a table with the following column:

NOTEID      NUMBER NOT NULL,

For all intents and purposes, this column is the primary key. This table has a few thousand rows, each with a unique ID. Before, the application would SELECT the MAX() value from the table, add one, then use that as the next value. This is a horrible solution, and is not transaction or thread safe (in fact, before they didn't even have a UNIQUE constraint on the column and I could see the same NOTEID was duplicated in 9 different occasions)..

I'm rather new to Oracle, so I'd like to know the best syntax to ALTER this table and make this column auto-increment instead. If possible, I'd like to make the next value in the sequence be the MAX(NOTEID) + 1 in the table, or just make it 800 or something to start out. Thanks!

like image 296
Mike Christensen Avatar asked Nov 29 '22 16:11

Mike Christensen


2 Answers

You can't alter the table. Oracle doesn't support declarative auto-incrementing columns. You can create a sequence

CREATE SEQUENCE note_seq
  START WITH 800
  INCREMENT BY 1
  CACHE 100;

Then, you can create a trigger

CREATE OR REPLACE TRIGGER populate_note_id
  BEFORE INSERT ON note
  FOR EACH ROW
BEGIN
  :new.note_id := note_seq.nextval;
END;

or, if you want to allow callers to specify a non-default NOTE_ID

CREATE OR REPLACE TRIGGER populate_note_id
  BEFORE INSERT ON note
  FOR EACH ROW
BEGIN
  IF( :new.note_id is null )
  THEN 
    :new.note_id := note_seq.nextval;
  END IF;
END;
like image 154
Justin Cave Avatar answered Dec 06 '22 20:12

Justin Cave


If your MAX(noteid) is 799, then try:

CREATE SEQUENCE noteseq
    START WITH 800
    INCREMENT BY 1

Then when inserting a new record, for the NOTEID column, you would do:

noteseq.nextval
like image 23
roartechs Avatar answered Dec 06 '22 18:12

roartechs