Auto Increment for Oracle

David Garcia picture David Garcia · Mar 16, 2012 · Viewed 69.8k times · Source

I need to create a sequence and a trigger to auto-increment the primary key on a table but I have no idea on how to do it.

Answer

Justin Cave picture Justin Cave · Mar 16, 2012

Create the table and the sequence

SQL> create table staff (
  2    emp_id number primary key,
  3    staff_name varchar2(100)
  4  );

Table created.

SQL> create sequence emp_id_seq;

Sequence created.

Now, you can create a trigger that uses the sequence to populate the primary key

SQL> create trigger trg_emp_id
  2    before insert on staff
  3    for each row
  4  begin
  5    select emp_id_seq.nextval
  6      into :new.emp_id
  7      from dual;
  8  end;
  9  /

Trigger created.

Now, when you insert data, you woon't need to specify the EMP_ID column-- it will automatically be populated by the trigger

SQL> insert into staff( staff_name ) values ('Justin');

1 row created.

SQL> select * from staff;

    EMP_ID STAFF_NAME
---------- --------------------
         1 Justin