Skip to Main Content
  • Questions
  • Triggers for sequences and audit columns

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Brad.

Asked: April 15, 2016 - 2:55 pm UTC

Last updated: April 15, 2016 - 3:21 pm UTC

Version: 11g Release 11.2.0.3.0

Viewed 1000+ times

You Asked

I have googled high and low for any opinion on this question with no success.

I noticed that many developers use triggers for getting sequence nextval and for populating columns of audit type information vs. including these columns into CRUD procedures.

Version 12 new column types aside, is there an argument to be made that the trigger method is a better practice?

Here is a sample that happens to be from an Application Express application but my question is general.
CREATE OR REPLACE TRIGGER BIU_PRJ_USER_AUTHS_TRG
BEFORE INSERT OR UPDATE ON PRJ_USER_AUTHS
REFERENCING OLD AS OLD NEW AS NEW 
FOR EACH ROW 
BEGIN

  IF INSERTING THEN
    :NEW.user_auth_id := prj_user_auth_seq.NEXTVAL;
    :NEW.created_by   := NVL(v('APP_USER'), USER);
    :NEW.created_date := SYSDATE;
  END IF;

  :NEW.updated_by   := NVL(v('APP_USER'), USER);
  :NEW.updated_date := SYSDATE;

END;


Maybe it is because I started using Oracle 9i when triggers were more of a last resort but my preference has been to not use triggers this way.

It seems to me that such a trigger is just one more database object to have to keep track of while building and maintaining an application vs. putting this code into the procedure that is populating the rest of the data during CRUD transactions on a table.


Thanks.

and Chris said...

A couple of thoughts:

- The example shown means you can never supply your own primary key values. It always takes the sequence nextval.
- The trigger approach is slower than using the sequence directly in your SQL. Depending on your environment this could be a significant overhead.

So personally I prefer to call the sequence directly in the procedure, not the trigger.

You can also set the created_date to sysdate using column defaults:

SQL> create table t (x int, y date default sysdate);

Table T created.

SQL> insert into t (x) values (1);

1 row inserted.

SQL> select x, y, sysdate from t;

         X Y                            SYSDATE
---------- ---------------------------- ----------------------------
         1 15-APR-16                    15-APR-16


Connor has a few blog posts covering this in more detail:

https://connormcdonald.wordpress.com/2014/04/24/really-dumb-triggers/
https://connormcdonald.wordpress.com/2012/01/22/updating-primary-keys-and-triggers/
https://connormcdonald.wordpress.com/2011/11/22/triggers/



Is this answer out of date? If it is, please let us know via a Comment

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library