Sub topic 2
Writing a PostgreSQL Trigger Function
This chapter assumes you know basic SELECT, INSERT, UPDATE, and DELETE, can create tables, and understand transactions. Familiarity with simple PL/pgSQL blocks is helpful.
A trigger function is a PostgreSQL function that runs automatically when a trigger detects an event. The event might be an insert, update, delete, or truncate. The function contains the database logic, while the trigger decides when PostgreSQL calls it.
The required function shape
A trigger function must return the special type trigger. It does not receive ordinary arguments in the function definition. Instead, PostgreSQL provides information about the event through special variables such as NEW, OLD, and TG_OP.
NEWcontains the row after a change. It is available forINSERTandUPDATE.OLDcontains the row before a change. It is available forUPDATEandDELETE.TG_OPcontains the operation name, such asINSERT,UPDATE, orDELETE.TG_TABLE_NAMEcontains the name of the table that fired the trigger.
This function copies the new email address to lowercase before PostgreSQL writes the row:
CREATE TABLE users (
user_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL
);
CREATE FUNCTION normalize_user_email() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.email := lower(trim(NEW.email));
RETURN NEW;
END;
$$;
CREATE TRIGGER users_normalize_email
BEFORE INSERT OR UPDATE OF email ON users
FOR EACH ROW
EXECUTE FUNCTION normalize_user_email();
INSERT INTO users (email) VALUES (' [email protected] ');
SELECT email FROM users;The query returns [email protected]. Because this is a BEFORE row-level trigger, changing NEW changes the row that will be stored.
How the function is called
The trigger supplies the context. The function does not need to know the values in advance.
A function can branch on TG_OP when one trigger handles multiple events:
CREATE FUNCTION describe_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
RAISE NOTICE 'created user %', NEW.user_id;
ELSIF TG_OP = 'DELETE' THEN
RAISE NOTICE 'deleted user %', OLD.user_id;
END IF;
RETURN NULL;
END;
$$;The return value matters. In a BEFORE row trigger, return NEW to continue with the row, return NULL to skip that row, or return another record to replace the row. In an AFTER trigger, PostgreSQL ignores the return value, so NULL is conventional.
Common design checks
| Question | Why it matters |
|---|---|
| Which event fires the trigger? | It determines whether `NEW` or `OLD` exists. |
| Is the trigger `BEFORE` or `AFTER`? | It determines whether the function can change the stored row. |
| Is it row-level? | It determines whether the function runs once per affected row. |
Exercise
For a BEFORE UPDATE row-level trigger, what should the function return when it has normalized NEW.email and wants PostgreSQL to save the change?
Show answer
It should return NEW.