Triggers

About

A trigger is an action or event that causes another event to occur. So a triggering SQL statement causes another SQL statement (the trigger statement) to be executed.

circle-info

Triggers can be used to:

  • Keep a database consistent;

  • Auditing events;

  • Logging;

  • Enforcing complex constraints;

  • Replications and more.

A PostgreSQL trigger is a function invoked automatically whenever 'an event' associated with a table occurs - like (Insert, Update, Delete or Truncate)

A trigger can be associated with a specific Table, View or Foreign Table.

Triggers can trigger:

  • BEFORE: If the trigger is invoked before an event, it can skip the operation for the current row or even change the row being updated or inserted.

  • AFTER: All changes are available to the trigger.

  • INSTEAD: Of the events/operation.

circle-exclamation
circle-check
triangle-exclamation

Types of triggers

Row level triggers

If the trigger is marked for each row, then the trigger function will be called for each row that is getting modified by the event.

Statement level triggers

The FOR EACH STATEMENT option will call the trigger function only once for each statement, regardless of the number of the rows getting modified.

Limitations

When
Event
Row-level only for
Statement-level only for

BEFORE

INSERT / UPDATE / DELETE

Tables

Tables and Views

TRUNCATE

Tables

AFTER

INSERT / UPDATE / DELETE

Tables

Tables and Views

TRUNCATE

Tables

INSTEAD OF

INSERT / UPDATE / DELETE

Views

TRUNCATE

Creating

  1. First, create a trigger function.

  2. Then, bind the trigger function to a table.

Trigger function

circle-info

You can sufix with trigger on function that are trigger functions.

Bind the trigger function

circle-info

You can use trg prefix on trigger names when creating them.

Deleting

Special variables

Triggers have special OLD and NEW variables to access values, which:

  • OLD represents the values before the event.

  • NEW represents the values after.

Depending on the event they can be NULL.

Usage

Using triggers for auditing

Last updated