Sub topic 1
What a Trigger Is and When to Use One
A PostgreSQL trigger is a database object that automatically runs a function when a specified database event occurs. Common events include INSERT, UPDATE, DELETE, and TRUNCATE. The trigger runs inside the same transaction as the event, so an error in the trigger can abort the change.
A trigger has three main parts:
- An event, such as an update to a table.
- A timing, such as before or after the event.
- A trigger function, which contains the PL/pgSQL code to run.
The function must return the special trigger type. The trigger decides when the function runs; the function decides what work to perform.
CREATE FUNCTION check_account_email() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.email = '' THEN
RAISE EXCEPTION 'email cannot be empty';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER accounts_email_check
BEFORE INSERT OR UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION check_account_email();This trigger checks each new or changed row before PostgreSQL writes it. NEW represents the row that would be inserted or the modified version of an updated row.
Prerequisites
This chapter assumes basic SQL, including SELECT, INSERT, UPDATE, DELETE, and CREATE TABLE. You should also understand transactions and have access to PostgreSQL through psql or another client. Familiarity with basic PL/pgSQL is helpful.
Triggers Compared with Other Options
A constraint states a rule that PostgreSQL can check directly. For example, NOT NULL, CHECK, UNIQUE, and foreign keys are usually better than triggers for simple data validity rules. Constraints are visible in the table definition and are easier for PostgreSQL to optimize.
A PostgreSQL rule is a rewrite instruction. It changes how a SQL command is transformed before execution. Rules are mainly associated with views and query rewriting. Triggers run procedural functions in response to events and are usually easier to reason about for row-level behavior.
Application code runs outside the database. It can provide user-facing validation and coordinate external services, but it cannot protect data from every client unless every client uses that code. A trigger protects the database regardless of whether the change comes from an application, a script, or an administrator.
Use a trigger when the behavior must happen automatically at the database boundary, such as recording an audit row or maintaining a derived value. Avoid triggers when an explicit constraint or clear application operation expresses the rule better. Hidden side effects can surprise developers and can add work to every matching statement.
Exercise
Which mechanism is usually the best first choice for requiring that an account balance is not negative: a CHECK constraint, a trigger, or application validation? Why?
Show answer
A CHECK constraint is usually best because it states the rule directly in the schema and protects all database clients without procedural side effects.