SQL Triggers
How triggers run code automatically when data changes: BEFORE and AFTER triggers, row and statement level, NEW and OLD, timestamps, rule enforcement, audit logs, transition tables, INSTEAD OF triggers, a closure table and its drift check, and when to avoid triggers.
kvi5hnuCode Sprout team member12 min readOn this page
A trigger runs a function automatically whenever a table's data changes: on INSERT, UPDATE, DELETE or TRUNCATE. No application has to remember to call it, so a trigger is a way to make something always happen, whichever program or person changes the data.
Triggers are powerful and easy to overuse. This article covers how they work, the common good uses (timestamps, rule enforcement, audit trails, derived data and writable views), an example of derived data drifting out of step, and the costs that make many teams use triggers sparingly.
How triggers work
A trigger has two parts in PostgreSQL:
- A trigger function, written in PL/pgSQL or another language, declared
RETURNS trigger. - A
CREATE TRIGGERstatement that attaches the function to a table, saying when it fires.

The choices when creating a trigger:
| Choice | Options |
|---|---|
| timing | BEFORE the change, AFTER it, or INSTEAD OF it (views only) |
| events | INSERT, UPDATE (optionally UPDATE OF column), DELETE, TRUNCATE, or several with OR |
| level | FOR EACH ROW, once per affected row, or FOR EACH STATEMENT, once per statement, even if no rows are affected |
| condition | an optional WHEN (...) that decides whether the trigger fires at all |
Inside a row-level trigger function, NEW holds the new row (for INSERT and UPDATE) and OLD holds the old row (for UPDATE and DELETE). Other special variables describe the event: TG_OP is 'INSERT', 'UPDATE', 'DELETE' or 'TRUNCATE', TG_TABLE_NAME is the table, and TG_WHEN and TG_LEVEL give the timing and level.
Triggers run inside the statement's transaction. If a trigger raises an error, the whole statement fails and is undone, and whatever the trigger did is undone with it.
BEFORE triggers: changing the row
A BEFORE ROW trigger runs before the row is written, and its return value decides what's written: return NEW, possibly changed, to write it, or return NULL to skip the row silently.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- BEFORE triggers can change the row being written: keep updated_at current
ALTER TABLE products ADD COLUMN updated_at TIMESTAMP NOT NULL DEFAULT TIMESTAMP '2026-01-01 00:00';
CREATE FUNCTION set_updated_at() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.updated_at := TIMESTAMP '2026-03-31 09:00'; -- real code: NEW.updated_at := now();
RETURN NEW; -- the row to write
END
$$;
CREATE TRIGGER products_updated_at
BEFORE UPDATE ON products
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*) -- only when something actually changed
EXECUTE FUNCTION set_updated_at();
UPDATE products SET price = 29.00 WHERE product_id = 4;
UPDATE products SET price = price WHERE product_id = 5; -- no real change
SELECT product_id, name, price, updated_at FROM products WHERE product_id IN (4, 5) ORDER BY product_id;
product_id | name | price | updated_at
------------+-------------------+-------+---------------------
4 | Basecamp lantern | 29.00 | 2026-03-31 09:00:00
5 | Trail 30 backpack | 89.95 | 2026-01-01 00:00:00
(2 rows)
The trigger sets updated_at whenever a product changes. The example uses a fixed timestamp so its output is repeatable. Real code would use now(). The WHEN (OLD.* IS DISTINCT FROM NEW.*) condition makes it fire only when something actually changed: the lantern's price change updates the timestamp, while the backpack's "update" to the same price doesn't.
Keeping updated_at, normalising values (trimming text, lower-casing emails) and filling in derived columns are classic uses of BEFORE triggers. For values computed only from the row's own columns, a generated column (article 52) is simpler.
Enforcing rules
A BEFORE trigger can also reject changes by raising an error. That's useful for rules involving other rows or tables, which CHECK constraints can't express:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A BEFORE trigger enforcing a rule that a CHECK constraint can't express
CREATE FUNCTION no_lines_on_closed_orders() RETURNS trigger
LANGUAGE plpgsql
AS $$
DECLARE
v_status TEXT;
BEGIN
SELECT status INTO v_status FROM orders WHERE order_id = NEW.order_id;
IF v_status IN ('shipped', 'delivered', 'cancelled') THEN
RAISE EXCEPTION 'order % is %, so its lines can''t change', NEW.order_id, v_status;
END IF;
RETURN NEW;
END
$$;
CREATE TRIGGER order_items_open_orders_only
BEFORE INSERT OR UPDATE ON order_items
FOR EACH ROW EXECUTE FUNCTION no_lines_on_closed_orders();
INSERT INTO orders VALUES (107, 2, DATE '2026-03-30', 'pending');
INSERT INTO order_items VALUES (107, 7, 2, 16.00); -- pending order: fine
INSERT INTO order_items VALUES (101, 4, 1, 27.00); -- shipped order: refused
SELECT order_id, product_id, qty FROM order_items WHERE order_id IN (101, 107) ORDER BY order_id, product_id;
psql:/workspace/solution.sql:83: ERROR: order 101 is shipped, so its lines can't change
CONTEXT: PL/pgSQL function no_lines_on_closed_orders() line 7 at RAISE
order_id | product_id | qty
----------+------------+-----
101 | 1 | 1
101 | 7 | 3
107 | 7 | 2
(3 rows)
Order lines can be added to the new pending order 107, but not to order 101, which has shipped. The rule holds for every application and every ad hoc script.
Triggers that check other tables have a weakness under concurrency: the trigger reads order 101's status, but another transaction could change that status at the same moment, and in READ COMMITTED neither sees the other's uncommitted change (article 61). For rules that must hold under concurrent changes, lock the row the check depends on (SELECT ... FOR UPDATE or FOR SHARE), or use SERIALIZABLE.
Audit trails with AFTER triggers
An AFTER trigger runs once the change has been made and its constraints checked, so it's the place to react to changes that will definitely happen, unless the transaction later rolls back:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- An AFTER trigger writing an audit trail, with OLD and NEW as JSON
CREATE TABLE audit_log (
audit_id INTEGER GENERATED ALWAYS AS IDENTITY,
table_name TEXT,
operation TEXT,
old_row JSONB,
new_row JSONB
);
CREATE FUNCTION audit_changes() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO audit_log (table_name, operation, old_row, new_row)
VALUES (TG_TABLE_NAME, TG_OP,
CASE WHEN TG_OP IN ('UPDATE', 'DELETE') THEN to_jsonb(OLD) END,
CASE WHEN TG_OP IN ('INSERT', 'UPDATE') THEN to_jsonb(NEW) END);
RETURN NULL; -- the return value of an AFTER trigger is ignored
END
$$;
CREATE TRIGGER customers_audit
AFTER INSERT OR UPDATE OR DELETE ON customers
FOR EACH ROW EXECUTE FUNCTION audit_changes();
INSERT INTO customers (customer_id, name, city) VALUES (7, 'Gita Bose', 'York');
UPDATE customers SET city = 'Leeds' WHERE customer_id = 7;
DELETE FROM customers WHERE customer_id = 7;
SELECT audit_id, operation,
old_row ->> 'city' AS old_city,
new_row ->> 'city' AS new_city
FROM audit_log ORDER BY audit_id;
audit_id | operation | old_city | new_city
----------+-----------+----------+----------
1 | INSERT | (null) | York
2 | UPDATE | York | Leeds
3 | DELETE | Leeds | (null)
(3 rows)
One generic function audits any table: TG_OP says what happened, and to_jsonb(OLD) and to_jsonb(NEW) capture whole rows as JSON (article 43), so the function doesn't need to know the table's columns. Gita's insert, move to Leeds and deletion are all recorded. The return value of an AFTER row trigger is ignored, so it returns NULL.
Real audit tables add who made the change (current_user, or an application user passed in a session setting) and when (now()), and are protected so ordinary roles can insert but not change or delete entries. Extensions such as pgAudit, and change data capture through logical replication, are alternatives for heavy auditing needs.
Statement-level triggers and transition tables
A row-level trigger on a statement that changes 100,000 rows runs 100,000 times. A statement-level trigger runs once, and with transition tables it can still see every changed row:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A statement-level trigger with a transition table: one call per statement, not per row
CREATE TABLE stock_moves (moved_on DATE, products INTEGER, units INTEGER);
CREATE FUNCTION log_restock() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO stock_moves
SELECT DATE '2026-03-31', COUNT(*), SUM(n.stock - o.stock)
FROM new_rows n JOIN old_rows o USING (product_id);
RETURN NULL;
END
$$;
CREATE TRIGGER products_restock
AFTER UPDATE ON products
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows
FOR EACH STATEMENT EXECUTE FUNCTION log_restock();
UPDATE products SET stock = stock + 10 WHERE category IN ('tents', 'packs');
SELECT * FROM stock_moves;
moved_on | products | units
------------+----------+-------
2026-03-31 | 4 | 40
(1 row)
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows makes the statement's before and after rows available as tables inside the trigger function, which can process them with one set-based query (article 63). The restock of tents and packs is logged as a single summary row: four products, 40 units. For bulk changes this is much faster than a row-level trigger.
INSTEAD OF triggers on views
A view that joins tables can't be updated automatically (article 56). An INSTEAD OF trigger tells the database what an insert, update or delete on the view should do instead:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- INSTEAD OF: make a join view writable by saying what an insert means
CREATE VIEW order_lines AS
SELECT oi.order_id, p.name AS product, oi.qty, oi.unit_price
FROM order_items oi JOIN products p ON p.product_id = oi.product_id;
CREATE FUNCTION order_lines_insert() RETURNS trigger
LANGUAGE plpgsql
AS $$
DECLARE
v_product products%ROWTYPE;
BEGIN
SELECT * INTO STRICT v_product FROM products WHERE name = NEW.product;
INSERT INTO order_items (order_id, product_id, qty, unit_price)
VALUES (NEW.order_id, v_product.product_id, NEW.qty, COALESCE(NEW.unit_price, v_product.price));
RETURN NEW;
END
$$;
CREATE TRIGGER order_lines_insert
INSTEAD OF INSERT ON order_lines
FOR EACH ROW EXECUTE FUNCTION order_lines_insert();
INSERT INTO order_lines (order_id, product, qty) VALUES (104, 'Merino socks', 3);
SELECT * FROM order_lines WHERE order_id = 104 ORDER BY product;
order_id | product | qty | unit_price
----------+---------------+-----+------------
104 | Merino socks | 3 | 16.00
104 | Summit 4 tent | 1 | 489.00
(2 rows)
order_lines shows lines with the product's name, not its ID. The trigger looks up the product by name and inserts the real order_items row, using the current price when none is given. Applications and users can work with the friendlier view, while the trigger translates.
Keeping derived data in step: a closure table
Article 48 introduced the closure table, which stores every (ancestor, descendant) pair in a tree so that subtree queries need no recursion. It must be kept in step with the tree itself, and a trigger is the usual way:
-- A category tree stored as an adjacency list: each row points to its parent
CREATE TABLE categories (
cat_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories (cat_id),
code TEXT -- matches products.category for the categories that have products
);
INSERT INTO categories VALUES
(1, 'Outdoor', NULL, NULL),
(2, 'Camping', 1, NULL),
(3, 'Tents', 2, 'tents'),
(4, 'Lighting', 2, 'lighting'),
(5, 'Hiking', 1, NULL),
(6, 'Packs', 5, 'packs'),
(7, 'Clothing', 5, 'clothing'),
(8, 'Socks', 7, NULL);
-- A closure table kept in step with the tree by a trigger
CREATE TABLE category_paths (ancestor INTEGER, descendant INTEGER, depth INTEGER,
PRIMARY KEY (ancestor, descendant));
INSERT INTO category_paths
WITH RECURSIVE p AS (
SELECT cat_id AS ancestor, cat_id AS descendant, 0 AS depth FROM categories
UNION ALL
SELECT p.ancestor, c.cat_id, p.depth + 1
FROM p JOIN categories c ON c.parent_id = p.descendant
)
SELECT * FROM p;
CREATE FUNCTION add_category_paths() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO category_paths VALUES (NEW.cat_id, NEW.cat_id, 0); -- itself
INSERT INTO category_paths -- every ancestor of its parent
SELECT ancestor, NEW.cat_id, depth + 1
FROM category_paths WHERE descendant = NEW.parent_id;
RETURN NULL;
END
$$;
CREATE TRIGGER categories_closure
AFTER INSERT ON categories
FOR EACH ROW EXECUTE FUNCTION add_category_paths();
INSERT INTO categories VALUES (9, 'Head torches', 4, NULL); -- under Lighting
SELECT c.name, cp.depth
FROM category_paths cp JOIN categories c ON c.cat_id = cp.ancestor
WHERE cp.descendant = 9
ORDER BY cp.depth;
-- The trigger only handles inserts. Moving a category silently breaks the closure table:
UPDATE categories SET parent_id = 5 WHERE cat_id = 4; -- Lighting moves under Hiking
-- A drift check: compare the stored pairs with pairs recomputed from the tree
WITH RECURSIVE p AS (
SELECT cat_id AS ancestor, cat_id AS descendant, 0 AS depth FROM categories
UNION ALL
SELECT p.ancestor, c.cat_id, p.depth + 1
FROM p JOIN categories c ON c.parent_id = p.descendant
)
SELECT 'missing' AS problem, * FROM (SELECT * FROM p EXCEPT SELECT * FROM category_paths) m
UNION ALL
SELECT 'stale', * FROM (SELECT * FROM category_paths EXCEPT SELECT * FROM p) s
ORDER BY problem, ancestor, descendant;
name | depth
--------------+-------
Head torches | 0
Lighting | 1
Camping | 2
Outdoor | 3
(4 rows)
problem | ancestor | descendant | depth
---------+----------+------------+-------
missing | 5 | 4 | 1
missing | 5 | 9 | 2
stale | 2 | 4 | 1
stale | 2 | 9 | 2
(4 rows)
The AFTER INSERT trigger adds the new category's path to itself, then one path from each ancestor of its parent, one level deeper. Inserting "Head torches" under Lighting automatically creates its paths to Lighting, Camping and Outdoor.
But the trigger only handles inserts. When Lighting is moved from Camping to Hiking by updating its parent_id, nothing updates the closure table, and it silently drifts from the truth. The drift check recomputes the pairs from the tree with a recursive CTE (article 25) and compares them with the stored ones using EXCEPT (article 15):
- missing pairs: Hiking is now an ancestor of Lighting and Head torches, but the closure table doesn't know.
- stale pairs: the closure table still says Camping is their ancestor.
Outdoor's pairs are unaffected, because Lighting is still two levels below it. Queries using the closure table would now give wrong answers about Hiking and Camping.
The lessons apply to any derived data maintained by triggers, such as summary tables, counters and denormalised copies:
- Handle every operation that can change the source: here, also
UPDATE OF parent_id(delete the moved subtree's paths to its old ancestors and add paths to the new ones) andDELETE. - Run a drift check like this one regularly, or in tests, to catch gaps in the trigger logic and changes made while triggers were disabled.
- Consider whether the derived data is needed at all. A recursive query, or a materialized view refreshed on a schedule (article 56), avoids the maintenance burden at the cost of speed or freshness.
The costs of triggers
Triggers have real drawbacks, which is why many teams limit them to a few well-understood uses:
- They're invisible. Someone reading application code, or running an
UPDATE, doesn't see that a trigger also writes to three other tables. Surprising side effects make bugs hard to find. - They slow writes. Row-level triggers run for every row, inside the transaction. Bulk loads with triggers can be many times slower.
- They can cascade. A trigger that updates another table can fire that table's triggers, and so on. A trigger that updates its own table can recurse. Guard against it with a
WHENcondition that stops the trigger once it has done its work, or checkpg_trigger_depth()inside the function. - Ordering. Several triggers for the same event on the same table fire in alphabetical order of their names in PostgreSQL, which is easy to get wrong when adding one. Other databases differ: Oracle and MySQL have
FOLLOWS/PRECEDESclauses, and SQL Server only lets you choose the first and last. - Bulk tools may bypass them.
TRUNCATEdoesn't fireDELETEtriggers, and administrators can disable triggers for data loads. Derived data can drift, as above.
Good uses: updated_at columns, audit logs, rules that constraints can't express, writable views, and derived data with a drift check. Questionable uses: business workflows such as sending emails or calling services (do these in the application, or from a queue table processed outside the transaction), and long chains of triggers that implement application logic.
Triggers in other databases
| PostgreSQL | Oracle | SQL Server | MySQL | |
|---|---|---|---|---|
| code | a separate trigger function | PL/SQL in the trigger body | T-SQL in the trigger body | SQL in the trigger body |
| row level | FOR EACH ROW, NEW / OLD | FOR EACH ROW, :NEW / :OLD | none: statement level only | FOR EACH ROW, NEW / OLD |
| statement level | yes, with transition tables | yes, and compound triggers | yes, with inserted and deleted tables | no |
INSTEAD OF on views | yes | yes | yes | no |
SQL Server's triggers always fire once per statement, with the changed rows in the inserted and deleted pseudo-tables, so a trigger written as if only one row changed is a common SQL Server bug. PostgreSQL also has event triggers, which fire on DDL commands such as CREATE TABLE, useful for enforcing schema conventions.
Oracle's mutating-table rule and compound triggers
In Oracle, a row-level trigger can't query or change the table that fired it: doing so raises ORA-04091, table is mutating, because the table is half-changed at that moment. A common case is a trigger on order_items that checks the order's total by reading order_items. The usual fixes are a statement-level AFTER trigger, which runs once the statement has finished, or a compound trigger, which has BEFORE STATEMENT, BEFORE EACH ROW, AFTER EACH ROW and AFTER STATEMENT sections sharing variables: the row sections collect the changed keys, and the AFTER STATEMENT section processes them.
PostgreSQL has no such rule. Row triggers can query their own table, though AFTER statement triggers with transition tables, shown earlier, are usually the cleaner way to check rules across many rows.
Triggers on schema changes
Triggers can also fire on DDL rather than data changes, for auditing or blocking schema changes. PostgreSQL has event triggers:
CREATE FUNCTION log_ddl() RETURNS event_trigger LANGUAGE plpgsql AS $$
DECLARE r RECORD;
BEGIN
FOR r IN SELECT * FROM pg_event_trigger_ddl_commands() LOOP
RAISE NOTICE '% on %', r.command_tag, r.object_identity;
END LOOP;
END
$$;
CREATE EVENT TRIGGER audit_ddl ON ddl_command_end EXECUTE FUNCTION log_ddl();
Creating event triggers needs superuser rights. Oracle has schema and database triggers, such as AFTER CREATE ON SCHEMA and AFTER LOGON ON DATABASE, and SQL Server has DDL triggers (CREATE TRIGGER ... ON DATABASE FOR CREATE_TABLE) and logon triggers.
What's current
- PostgreSQL 17 added
MERGE ... RETURNING, and allowedMERGEon views that are automatically updatable or haveINSTEAD OFtriggers for every action used (views with rules aren't supported).MERGEhas fired the matchingINSERT,UPDATEandDELETEtriggers since it arrived in PostgreSQL 15. - PostgreSQL 13 allowed
BEFORErow triggers on partitioned tables, applying to every partition, and PostgreSQL 11 addedEXECUTE FUNCTIONas the preferred spelling ofEXECUTE PROCEDURE. CREATE OR REPLACE TRIGGERexists since PostgreSQL 14.
Common questions
BEFORE or AFTER?
BEFORE to change or reject the row being written. AFTER to react to a change that has been made, for example writing an audit row or updating other tables.
Row level or statement level? Row level when each row needs separate handling. Statement level, with transition tables, for set-based work on bulk changes.
Why didn't my trigger fire?
Check its events (UPDATE OF column fires only when that column is in the SET list), its WHEN condition, whether it's disabled, and whether the change was made by TRUNCATE or another command it doesn't cover.
Can a trigger stop a change?
Yes. A BEFORE row trigger can raise an error, rejecting the statement, or return NULL to skip that row silently.
Should I use triggers for business logic? Sparingly. They're best for integrity, auditing and keeping derived data in step. Workflows and integrations are easier to understand and test in the application.
Summary
- A trigger runs a function automatically when rows are inserted, updated, deleted or truncated.
BEFORErow triggers can modifyNEWor skip the row.AFTERtriggers react to completed changes.- Row-level triggers run per row. Statement-level triggers run once and can use transition tables.
- Triggers run inside the transaction: their errors undo the statement, and their work is undone with it.
- Common uses:
updated_at, rule enforcement, audit logs, writable views withINSTEAD OF, and derived data. - Derived data maintained by triggers can drift if any change path is missed. Check it.
- Triggers are invisible and slow bulk writes: keep them few, simple and well documented.
Practice questions
Write a trigger that stores emails in lower case on every insert and update of customers.email (assume the column was added with ALTER TABLE customers ADD COLUMN email TEXT).
Answer
CREATE FUNCTION lower_email() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.email := lower(NEW.email);
RETURN NEW;
END
$$;
CREATE TRIGGER customers_lower_email
BEFORE INSERT OR UPDATE OF email ON customers
FOR EACH ROW EXECUTE FUNCTION lower_email();
A BEFORE INSERT row trigger returns NULL. What happens to the row, and is an error raised?
Answer
The row isn't inserted, and no error is raised: the statement succeeds and reports one fewer row inserted. That silence is why returning NULL should be used deliberately.
An UPDATE changes 50,000 rows of a table with a row-level AFTER UPDATE audit trigger. How many times does the trigger function run, and what alternative would run it once?
Answer
50,000 times. A FOR EACH STATEMENT trigger with REFERENCING OLD TABLE ... NEW TABLE ... runs once and can insert all the audit rows with one INSERT ... SELECT.
The closure table trigger in this article handles only inserts. Name two other operations that can make it drift.
Answer
Updating a category's parent_id, which moves a subtree, and deleting a category, which leaves stale pairs (unless foreign keys prevent it). Disabling triggers during a bulk load, or TRUNCATE, can also make it drift.
Previous: Stored Procedures and Functions

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.