TExcelTAD
Home › PostgreSQL › PostgreSQL Triggers

PostgreSQL Triggers

A trigger runs a function automatically when something happens to a table: a row is inserted, updated or deleted. Triggers are used for audit logs, keeping derived columns up to date, and enforcing rules that are too complex for a CHECK constraint.

Creating a trigger takes two steps:

  1. a trigger function (PL/pgSQL, RETURNS trigger), and
  2. the trigger itself, which says when to call the function.

Example: keep an "updated" timestamp

pgsql · try it yourself
ALTER TABLE books ADD COLUMN updated_at timestamp;

CREATE FUNCTION touch_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $
BEGIN
    NEW.updated_at := TIMESTAMP '2025-06-01 12:00';  -- in real code: now()
    RETURN NEW;
END;
$;

CREATE TRIGGER books_touch
BEFORE UPDATE ON books
FOR EACH ROW EXECUTE FUNCTION touch_updated_at();

UPDATE books SET price = 15.49 WHERE id = 1;
SELECT id, title, price, updated_at FROM books WHERE id IN (1, 2);
ALTER TABLE
CREATE FUNCTION
CREATE TRIGGER
UPDATE 1
 id |     title     | price |     updated_at
----+---------------+-------+---------------------
  1 | The Salt Road | 15.49 | 2025-06-01 12:00:00
  2 | Harbor Lights | 12.50 |
(2 rows)

Inside a row trigger, NEW is the row as it will be written and OLD is the row as it was. A BEFORE trigger may change NEW; whatever it returns is what gets stored.

Variable Available in
NEW INSERT, UPDATE
OLD UPDATE, DELETE
TG_OP the operation: 'INSERT', 'UPDATE', 'DELETE'
TG_TABLE_NAME the table that fired the trigger

Example: an audit log

An AFTER trigger records every change of a price in a separate table:

pgsql · try it yourself
CREATE TABLE price_history (
    book_id   integer,
    old_price numeric(6,2),
    new_price numeric(6,2),
    action    text
);

CREATE FUNCTION log_price_change() RETURNS trigger
LANGUAGE plpgsql AS $
BEGIN
    INSERT INTO price_history VALUES (NEW.id, OLD.price, NEW.price, TG_OP);
    RETURN NULL;   -- the return value of AFTER triggers is ignored
END;
$;

CREATE TRIGGER books_price_audit
AFTER UPDATE OF price ON books
FOR EACH ROW
WHEN (OLD.price IS DISTINCT FROM NEW.price)
EXECUTE FUNCTION log_price_change();

UPDATE books SET price = price * 1.05 WHERE category_id = 2;
UPDATE books SET stock = stock + 1 WHERE id = 3;        -- price not touched: no log
UPDATE books SET price = 18.90 WHERE id = 3;             -- same price again: no log

SELECT * FROM price_history ORDER BY book_id;
CREATE TABLE
CREATE FUNCTION
CREATE TRIGGER
UPDATE 3
UPDATE 1
UPDATE 1
 book_id | old_price | new_price | action
---------+-----------+-----------+--------
       3 |     18.00 |     18.90 | UPDATE
       4 |     16.75 |     17.59 | UPDATE
       5 |     21.00 |     22.05 | UPDATE
(3 rows)

UPDATE OF price fires only when the price column appears in the SET list, and the WHEN condition skips updates that don't actually change it.

Example: enforcing a business rule

A BEFORE trigger can reject a row by raising an exception. Here an order line may not be added to an order that is already delivered or cancelled:

pgsql · try it yourself
CREATE FUNCTION check_order_open() RETURNS trigger
LANGUAGE plpgsql AS $
DECLARE
    st text;
BEGIN
    SELECT status INTO st FROM orders WHERE id = NEW.order_id;
    IF st IN ('delivered', 'cancelled') THEN
        RAISE EXCEPTION 'order % is %, it cannot be changed', NEW.order_id, st;
    END IF;
    RETURN NEW;
END;
$;

CREATE TRIGGER order_items_open_only
BEFORE INSERT OR UPDATE ON order_items
FOR EACH ROW EXECUTE FUNCTION check_order_open();

INSERT INTO order_items VALUES (18, 1, 1, 14.99);   -- order 18 is pending
INSERT INTO order_items VALUES (1, 2, 1, 12.50);    -- order 1 is delivered
SELECT order_id, book_id FROM order_items WHERE order_id IN (1, 18) ORDER BY 1, 2;
CREATE FUNCTION
CREATE TRIGGER
INSERT 0 1
ERROR:  order 1 is delivered, it cannot be changed
CONTEXT:  PL/pgSQL function check_order_open() line 7 at RAISE
 order_id | book_id
----------+---------
        1 |       1
        1 |       8
       18 |       1
       18 |       9
(4 rows)

Example: keeping stock in sync

Triggers can change other tables. When an order line is inserted, reduce the book's stock automatically:

pgsql · try it yourself
CREATE FUNCTION take_from_stock() RETURNS trigger
LANGUAGE plpgsql AS $
BEGIN
    UPDATE books SET stock = stock - NEW.quantity WHERE id = NEW.book_id;
    RETURN NEW;
END;
$;

CREATE TRIGGER order_items_stock
AFTER INSERT ON order_items
FOR EACH ROW EXECUTE FUNCTION take_from_stock();

SELECT stock FROM books WHERE id = 13;
INSERT INTO order_items VALUES (19, 13, 3, 8.99);
SELECT stock FROM books WHERE id = 13;
INSERT INTO order_items VALUES (18, 16, 2, 17.80);   -- only 1 copy left
CREATE FUNCTION
CREATE TRIGGER
 stock
-------
    30
(1 row)

INSERT 0 1
 stock
-------
    27
(1 row)

ERROR:  new row for relation "books" violates check constraint "books_stock_check"
DETAIL:  Failing row contains (16, Winter in Sofia, 8, 1, 17.80, -1, 2024-12-01, {city,winter}, {"pages": 264, "format": "ebook", "language": "bg"}).
CONTEXT:  SQL statement "UPDATE books SET stock = stock - NEW.quantity WHERE id = NEW.book_id"
PL/pgSQL function take_from_stock() line 3 at SQL statement

The last insert fails: the trigger's UPDATE would make the stock negative, the CHECK constraint on books rejects it, and the whole statement (including the order line) is rolled back.

Row vs statement triggers, and managing triggers

FOR EACH ROW runs once per affected row; FOR EACH STATEMENT runs once per statement, even if it changes no rows. Triggers can be disabled with ALTER TABLE … DISABLE TRIGGER name and removed with DROP TRIGGER name ON table.

Tip: Triggers are invisible when reading the application code, which can make behaviour surprising. Use them for things that must always happen (audit, integrity), keep them short, and document them.

Test yourself

In a BEFORE UPDATE row trigger, how do you change the value that will be stored?

  1. Modify OLD
  2. Modify NEW and RETURN NEW
  3. Run another UPDATE
  4. It's not possible

Which record holds the previous version of a row in an UPDATE trigger?

  1. NEW
  2. OLD
  3. TG_OP
  4. PREVIOUS

What happens when a trigger function raises an exception?

  1. Only the trigger is skipped
  2. The statement that fired it fails and its changes are rolled back
  3. The error is logged and ignored
  4. The table is locked