Search notes:

Oracle: Using a trigger and a sequence to provide the values for a primary key

A table for the example:
create table tq84_trigger_test (
    id   integer primary key,
    val  number(6,2)
);
The following sequence provides the values for the primary key:
create sequence tq84_trigger_seq;
The followng trigger is executed when an insert statement is executed on the table. It uses the sequence to assign a value to the id if the insert statement does not explicitly provide one:
create or replace trigger tq84_trigger_test
   before insert on tq84_trigger_test
   for each row
begin
   if :new.id is null then
      :new.id := tq84_trigger_seq.nextval;
   end if;
end;
/
Trigger in action:
insert into tq84_trigger_test (    val) values (      7.81);
insert into tq84_trigger_test (id, val) values (9999, 4.18);

select * from tq84_trigger_test;
Cleaning up:
drop table    tq84_trigger_test;
drop sequence tq84_trigger_seq;

See also

Automatic assignment for primary key

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1740465136, '13.59.244.1', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/databases/Oracle/objects/triggers/sequence-primary-key(68): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78