Auto increment for oracle

Oracle does *NOT* support auto_increment keys like mysql natively so there are different ways to emulate it.

Particularly I prefer to create a SEQUENCE and update it through a trigger.

-- Creation of table
CREATE TABLE user(
 user_id INTEGER NOT NULL ,
 name VARCHAR2(15),
 PRIMARY KEY ( user_id )
);

-- Creation of sequence
CREATE SEQUENCE seq_user_id
    START WITH 1
    INCREMENT BY 1
NOMAXVALUE;

-- Creation of trigger
CREATE TRIGGER trg_user_seq
BEFORE INSERT ON user
FOR EACH ROW
 BEGIN
   SELECT seq_user_id.nextval INTO :new.user_id 
     FROM dual;
 END;

Insert statement

    INSERT INTO user (name) VALUES('Francis');

Data Table

   USER_ID NAME           
---------- ---------------
         1 Francis            

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEN