Unlike SQL server, MySQL etc. Oracle doesn’t have identity columns. This is a bit of a pain when you need an auto incrementing column for a unique ID, which I use all the time as a primary key in the “many” table of a “one to many” relationship.
Oracle deals with this by using a sequence and a trigger attached to insert statements. This post from lifeaftercoffee describes the method I followed to get it to work:
First let’s create a simple table to play with.
SQL> CREATE TABLE test
(id NUMBER PRIMARY KEY,
Now we’ll assume we want ID to be an auto increment field. First we need a sequence to grab values from.
SQL> CREATE SEQUENCE test_sequence
START WITH 1
INCREMENT BY 1;
Now we can use that sequence in an
BEFORE INSERTtrigger on the table.
CREATE OR REPLACE TRIGGER test_trigger
REFERENCING NEW AS NEW
FOR EACH ROW
SELECT test_sequence.nextval INTO :NEW.ID FROM dual;
This trigger will automatically grab the next value from the sequence we just created and substitute it into the ID column before the insert is completed.
If you don’t want to use a trigger you can manually add the next value in the sequence during your insert statement:
insert into test values(test_sequence.nextval, ‘my data!’);