SQL fundamentals learning path Level 2 This level · 3 of 7
Medium postgresql sql

What are stored procedures and triggers, and when do you use each?

The 30 second answer

A stored procedure is a named routine in the database that I call explicitly, often to run several statements in one round trip. A trigger is a function the database runs automatically on INSERT, UPDATE, DELETE or TRUNCATE of a table. I use a procedure for an operation I want to invoke; I use a trigger for a constraint, audit row or derived column that must hold even if a client bypasses the application. In a Spring Boot service I still prefer keeping business flow in the application unless the work truly belongs next to the data.

Could you say this in an interview?

A stored procedure is a routine stored in the database and started with CALL. In PostgreSQL I create it with CREATE PROCEDURE and I can commit or roll back inside it, which a function used in a query cannot do. I use one when I want several statements, or a transactional unit, to run close to the data in a single round trip.

A trigger is not called by the application. I attach a function to a table with CREATE TRIGGER, and PostgreSQL runs it BEFORE, AFTER or INSTEAD OF a row or statement change. Typical uses are an audit row, a timestamp, or a check that is hard to express as a constraint. The important point in an interview is the difference in control: I decide when a procedure runs; a trigger runs whenever that table changes, including from psql, a migration, or another service.

CREATE TABLE account (
    id   bigint PRIMARY KEY,
    name text NOT NULL
);

CREATE TABLE account_audit (
    account_id bigint NOT NULL,
    changed_at timestamptz NOT NULL DEFAULT now(),
    action     text NOT NULL
);

CREATE PROCEDURE rename_account(p_id bigint, p_name text)
LANGUAGE sql
AS $$
    UPDATE account SET name = p_name WHERE id = p_id;
$$;

CREATE FUNCTION account_audit_change() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
    INSERT INTO account_audit(account_id, action)
    VALUES (NEW.id, TG_OP);
    RETURN NEW;
END;
$$;

CREATE TRIGGER account_audit_change
AFTER INSERT OR UPDATE ON account
FOR EACH ROW
EXECUTE FUNCTION account_audit_change();

CALL rename_account(1, 'Ada');

CALL rename_account is the procedure: it runs only when I invoke it. The trigger then inserts the audit row for that update, and it would also fire if I ran a plain UPDATE account from any client. In a Spring Boot service I keep most business flow in the application, and I reach for a procedure or trigger when the rule must be enforced in the database itself.

Sources (3)
  1. PostgreSQL: CREATE PROCEDUREpostgresql.org
  2. PostgreSQL: CREATE TRIGGERpostgresql.org
  3. PostgreSQL: Overview of trigger behaviorpostgresql.org
Previous
Next