While we have our table created and ready to go, our sequence is thus far just sitting there but never being put to use. This is where
TRIGGERS come in.
Similar to an
event in modern programming languages, a
TRIGGER in Oracle is a stored procedure that is executed when a particular event occurs.
TRIGGER will be configured to fire when a table is updated or a record is deleted, providing a bit of cleanup when necessary.
In our case, we want to execute our
TRIGGER prior to
INSERT into our
books table, ensuring our
SEQUENCE is incremented and that new value is passed onto our primary key column.
Here we are creating (or replacing if it exists) the
books_on_insert and specifying that we want the trigger to fire
BEFORE INSERT occurs for the
books table, and to be applicable to any and all rows therein.
The ‘code’ of the trigger itself is fairly simple: We
SELECT the next incremental value from our previously created
books_sequence SEQUENCE, and inserting that into the
:new record of the
books table in the specified
FROM dual part is necessary to complete a proper query but is effectively irrelevant. The
dual table is just a single dummy row of data and is added, in this case, just so it can be ignored and we can instead execute the system function of our trigger rather than returning data of some kind.
IDENTITY columns were introduced in Oracle 12c, allowing for simple auto increment functionality in modern versions of Oracle.
IDENTITY column is functionally similar to that of other database systems. Recreating our above
books table schema in modern Oracle 12c or higher, we’d simply use the following column definition.