Knowledge base / SQL

PostgreSQL TRIGGER: recording status changes

I explain one trigger that records actual status changes, with a small example and clear limits to that history.

Kajo RudzińskiPublished Updated 5 min read

A database activating a mechanical archive entry on a blank tile.

A trigger connects a database event with automatic execution of a function. I first define the event and whether the action concerns each row or the whole statement. Only then do I write the function body. This entry covers one narrow case: recording actual order-status changes in PostgreSQL 18. It is a synthetic exercise, without customer records or deployment to a company’s database.

The trigger and its function are separate objects

In PostgreSQL, first create a function returning trigger, then attach it to a table with CREATE TRIGGER. The function describes the action. The trigger definition specifies the event and timing. The PostgreSQL 18 overview explains the distinction. This is not portable syntax for every SQL engine. The old English entry mixed another dialect with the Polish example; both versions now describe the same objects.

I choose AFTER UPDATE because the history should describe a row change. AFTER means after the operation within its execution, rather than an independent action after transaction commit. This example does not need to modify NEW before writing or replace an operation on a view. Keeping one scenario makes the path from a statement to a history record easier to follow.

Define a small synthetic example

The demo_ names distinguish the example from existing objects. This fragment assumes a fresh practice environment where these names do not exist. It creates two tables, a function and a trigger; it is not a script for repeated execution against someone else’s database. CREATE TRIGGER documents the full syntax and condition behavior.

CREATE TABLE demo_orders (
    order_id integer PRIMARY KEY,
    status text
);

CREATE TABLE demo_order_history (
    order_id integer NOT NULL,
    old_status text,
    new_status text,
    changed_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE FUNCTION demo_log_status()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
    INSERT INTO demo_order_history (order_id, old_status, new_status)
    VALUES (NEW.order_id, OLD.status, NEW.status);
    RETURN NULL;
END;
$$;

CREATE TRIGGER demo_orders_status_changed
AFTER UPDATE OF status ON demo_orders
FOR EACH ROW
WHEN (OLD.status IS DISTINCT FROM NEW.status)
EXECUTE FUNCTION demo_log_status();

UPDATE OF status responds when status appears in the SET list. That alone does not guarantee a changed value. The IS DISTINCT FROM condition also handles NULL: NULL becoming text passes, while NULL remaining NULL does not. An ordinary <> comparison would not have the same behavior for missing values. See the comparison predicates for that distinction.

Understand OLD, NEW and RETURN

For a row-level UPDATE, OLD contains the previous row and NEW contains its new version. The history insert takes the new row’s identifier and both status values. This example treats order_id as a stable key and does not separately audit identifier changes. If a design allows those changes, establish how history should relate to the order rather than adding arbitrary fields to the function.

The return value of a row-level AFTER trigger is ignored, so I use RETURN NULL. That rule does not apply to every trigger. A row-level BEFORE trigger can alter or skip an operation through its return value. The trigger-function documentation explains the difference. The earlier blanket statement that triggers do not return values was therefore misleading: distinguish the return type from how a particular trigger uses it.

The matching $$ delimiters enclose the function-body string. A single $ is not a valid substitute. Matching named dollar delimiters are another option; this example uses the simplest pair. See the dollar-quoting rules. The semicolon after END belongs inside the body, while the semicolon after the closing delimiter finishes CREATE FUNCTION.

Trace a change step by step

Suppose the order table contains a synthetic row with order_id = 1 and status = 'new', and history is empty. Updating status to 'paid' passes the condition and adds a history record containing 1, 'new' and 'paid'. Assigning 'paid' again adds no history because old and new status match. This follows from the condition rather than merely from the presence of an UPDATE statement.

If a statement finds no order, this row trigger has no row to process. If it changes two matching orders to different statuses, it can add two records. Calls depend on affected rows and the condition, rather than on how many commands someone typed. PostgreSQL also supports statement triggers, but this example does not use one. Keep that boundary clear when interpreting the code.

Two mechanically linked drawers representing the change and its history within one transaction.

The history write shares the transaction

Rolling back the transaction also removes its history insert. If writing history raises an error, the update can fail too. The trigger overview documents this behavior. This mechanism records committed changes through ordinary transactional work. It is not an independent record of every failed attempt whose effects were subsequently rolled back.

The changed_at column uses CURRENT_TIMESTAMP, the start time of the current PostgreSQL transaction. Several changes within one transaction can therefore share it. Do not use that value as the sole ordering mechanism or a unique event identifier. The date and time documentation distinguishes transaction time from clock time. Here the timestamp is supporting information rather than an ordering guarantee.

Decide what belongs in a larger design

First consider whether a CHECK, foreign key or default solves the requirement more simply. A history trigger can be justified, but it introduces work that is not visible in an ordinary UPDATE. Its presence, permissions and cost on large updates need to be understood. I make no promise of improved performance. Every history record adds work whose significance depends on actual workload and data structure.

This example is not a tamper-resistant audit system. It does not protect the history table or identify an application user, and it does not send messages to an external service. Those requirements need a separate design. As an exercise, explain what happens when text becomes NULL and when a transaction rolls back. If you can explain both, you understand the main scope of this trigger. For related context, read about stored procedures.

Key takeaways

Is this syntax portable to every SQL engine?

No. It targets PostgreSQL 18 and PL/pgSQL functions; consult another engine’s documentation before translating it.

Does AFTER mean after transaction commit?

No. The trigger shares the transaction, and rolling it back also removes the history record.

Does assigning the same status add history?

Not in this example: its condition compares OLD.status and NEW.status using IS DISTINCT FROM.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.