An application runs one UPDATE. The status changes, and PostgreSQL records the old and new values in a second table—without a separate audit INSERT from the application. How does the database know what to do?
In this hands-on example, you will build two PostgreSQL triggers, see the actual results, and find out what happens when a transaction is rolled back. The example uses fictional data in temporary tables and does not change TrainingHub.
What is a trigger?
A trigger connects an event on a database object to a function that PostgreSQL runs automatically. Our event is an UPDATE on a table. The trigger definition says when and for which rows the function runs; the trigger function contains what to do. Creating the function or trigger does not itself update a row.
We will use a BEFORE UPDATE trigger to normalize the proposed status and an AFTER UPDATE trigger to record a change. Both are FOR EACH ROW: PostgreSQL considers each affected row separately. The WHEN condition on the second trigger restricts it to rows whose status actually differs. See the PostgreSQL trigger overview.
Before you begin
You need PostgreSQL and a SQL client such as pgAdmin's Query Tool or psql, permission to create temporary tables and functions, and basic familiarity with SELECT and UPDATE. This example was executed with psql against PostgreSQL 17.8; pgAdmin display and results can differ. Open one disposable learning session and run the blocks in order on the same connection. Temporary objects disappear when that session ends. The statements write to the temporary tables; they do not change TrainingHub.
In pgAdmin, select a block and use Execute/Run. If your client displays only the last result from multiple statements, run the statements individually to see each result. Starting again? Open a new connection and rerun setup; creating the same objects twice in the same session causes a name conflict.
1. Create the sample tables
CREATE TEMP TABLE demo_enrollments (
enrollment_id integer PRIMARY KEY,
status text NOT NULL
);
CREATE TEMP TABLE demo_status_audit (
enrollment_id integer NOT NULL,
old_status text NOT NULL,
new_status text NOT NULL
);
INSERT INTO demo_enrollments VALUES (1, 'active');
demo_enrollments holds one enrollment. demo_status_audit starts empty and will hold the before-and-after values. CREATE TEMP TABLE makes these session-local tables. We deliberately omit timestamps and user identity to keep the example focused.
2. Define a BEFORE trigger function
CREATE FUNCTION pg_temp.normalize_status() RETURNS trigger
LANGUAGE plpgsql AS $function$
BEGIN
NEW.status := lower(trim(NEW.status));
RETURN NEW;
END;
$function$;
CREATE FUNCTION gives the routine a name; pg_temp places it in the session's temporary schema. The empty parentheses mean no ordinary function parameters. RETURNS trigger identifies this as a trigger function, and LANGUAGE plpgsql chooses the procedural language. Matching $function$ tags surround the function body; the tag is a delimiter, not a variable.
For this row-level update, NEW represents the proposed new row. trim removes surrounding spaces, lower makes letters lowercase, and := assigns the result to NEW.status. RETURN NEW passes the modified row onward. This return value matters for a row-level BEFORE trigger: returning NULL instead would skip that row's operation. The exact return rules depend on trigger timing and event; see PL/pgSQL trigger functions.
3. Attach the BEFORE trigger
CREATE TRIGGER normalize_enrollment_status
BEFORE UPDATE ON demo_enrollments
FOR EACH ROW
EXECUTE FUNCTION pg_temp.normalize_status();
The trigger is named normalize_enrollment_status; it runs before updates to demo_enrollments, once for each affected row. EXECUTE FUNCTION identifies the trigger function. This example uses a PostgreSQL function returning trigger, not a procedure invoked with CALL.
4. Define and attach an AFTER trigger
CREATE FUNCTION pg_temp.record_status_change() RETURNS trigger
LANGUAGE plpgsql AS $function$
BEGIN
INSERT INTO pg_temp.demo_status_audit
(enrollment_id, old_status, new_status)
VALUES (NEW.enrollment_id, OLD.status, NEW.status);
RETURN NULL;
END;
$function$;
In this row-level UPDATE, OLD.status is the value before the update and NEW.status is the new value after our BEFORE normalization. The function inserts both into the audit table. PostgreSQL ignores the return value of an AFTER row trigger function, so this example uses RETURN NULL; it does not cancel the update.
CREATE TRIGGER audit_enrollment_status
AFTER UPDATE ON demo_enrollments
FOR EACH ROW
WHEN (OLD.status IS DISTINCT FROM NEW.status)
EXECUTE FUNCTION pg_temp.record_status_change();
AFTER UPDATE associates the function with completed updates. This ordinary AFTER row trigger runs at the end of the statement, still within the transaction. Its WHEN condition allows a log entry only when the old and new values differ. IS DISTINCT FROM also gives a definite comparison for NULL values, though both statuses in our sample tables are NOT NULL. Merely naming a column in UPDATE OF status is not the same as testing whether its value changed. See CREATE TRIGGER.
5. Update and inspect the result
UPDATE demo_enrollments
SET status = ' COMPLETED '
WHERE enrollment_id = 1;
SELECT * FROM demo_enrollments;
SELECT * FROM demo_status_audit;
In the tested run, the first result is 1 | completed. The audit result is 1 | active | completed. The BEFORE function trimmed and lowercased the proposed value; then the AFTER function recorded the transition. The SQL statement did not explicitly insert into the audit table.
What if we write the same status again?
UPDATE demo_enrollments
SET status = 'completed'
WHERE enrollment_id = 1;
SELECT count(*) AS audit_rows_after_same_status
FROM demo_status_audit;
The tested result is 1. The UPDATE still affects the matching row, but the AFTER trigger's condition is false for the unchanged normalized status, so no additional audit row is inserted.
6. What does ROLLBACK do?
Run setup and the previous blocks first, then execute these statements on the same connection. Use normal autocommit for the earlier blocks so that the sample objects and first change are established before the explicit transaction.
BEGIN;
UPDATE demo_enrollments SET status = 'cancelled' WHERE enrollment_id = 1;
SELECT status FROM demo_enrollments WHERE enrollment_id = 1;
SELECT count(*) AS audit_rows_before_rollback FROM demo_status_audit;
ROLLBACK;
SELECT * FROM demo_enrollments;
SELECT * FROM demo_status_audit;
Before ROLLBACK, the status is cancelled and the audit table has 2 rows in this session. After rollback, the status is completed and only 1 | active | completed remains in the audit table. The trigger and the statement run in the same transaction, so the rollback reverses both changes from this transaction. This also means a trigger error can cause the triggering statement to fail. See the PostgreSQL documentation on trigger behavior.
BEFORE, AFTER and scope: what to remember
- BEFORE row: can inspect or modify
NEWfor an INSERT or UPDATE; the appropriate returned row controls what happens next. - AFTER row: can react to the completed operation. This example records a status transition; it does not change the stored row by returning a different value.
- ROW versus STATEMENT: a row trigger is considered for each affected row; an applicable statement trigger is considered once per statement, including when zero rows are affected. WHEN conditions can restrict both.
- OLD and NEW: for an UPDATE row trigger both are available; their availability differs for INSERT, DELETE and statement triggers.
This small temporary audit table is a teaching example, not a complete security audit. It does not identify a person, prevent authorized changes to audit records, retain history after the session ends, or capture all database operations. Real systems need deliberate permissions, retention, monitoring, performance testing and a trustworthy identity strategy. Triggers add work and can hide side effects, so document them and measure behavior in your own workload.
Try it yourself
After setup in a fresh session, change the first status to ' ACTIVE '. Predict the normalized value and number of audit rows, then run the update and query both tables. Why does the condition avoid a new record? Next change it to 'completed' and check again.
For more hands-on SQL and PostgreSQL, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor's referral link. The example in this article is free and runs independently of the course.