Trigger WHEN Skips No-op Updates

Gate a trigger with WHEN (OLD IS DISTINCT FROM NEW) so equal-value updates never queue the trigger, while real changes fire it once per row.

SqlData Integrity

Code

snippet
CREATE TABLE accounts (
    id      integer PRIMARY KEY,
    balance numeric NOT NULL
);

-- WHEN 条件先于触发器函数求值;AFTER 行级触发器上条件为假
-- 即不排队触发事件(文档:can result in significant speedups)。
-- 作者约束:WHEN 表达式不能包含子查询;行级 INSERT 触发器不能引用 OLD、
-- DELETE 触发器不能引用 NEW(文档明文)
CREATE FUNCTION notify_transfer() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
    RAISE NOTICE 'balance % -> % for account %', OLD.balance, NEW.balance, NEW.id;
    RETURN NULL; -- AFTER 触发器的返回值被忽略
END $$;

CREATE TRIGGER accounts_notify
    AFTER UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
    EXECUTE FUNCTION notify_transfer();

INSERT INTO accounts VALUES (1, 500);

-- 等值更新:WHEN 为假,不排队触发事件,NOTICE 不会出现
UPDATE accounts SET balance = balance WHERE id = 1;

-- 真实变化:按行触发一次
UPDATE accounts SET balance = 500 - 80 WHERE id = 1;

-- 收尾清理:触发器声明是 AFTER UPDATE,DELETE 完全不经过它,
-- 因此这一步同样不会出现 NOTICE
DELETE FROM accounts WHERE id = 1;

The run, step by step

What runs here is INSERT / UPDATE / DELETE / CREATE — on, new.balance and accounts are the objects involved.

Mechanically, the statements are built from: a WHERE clause limiting a statement to the rows that qualify; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The on table is the working surface here.

Statements that matter

CREATE TRIGGER accounts_notify
    AFTER UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
    EXECUTE FUNCTION notify_transfer();
UPDATE accounts SET balance = 500 - 80 WHERE id = 1;
UPDATE accounts SET balance = balance WHERE id = 1;

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`on`, `new.balance`, `accounts` — referenced directly, no join needed.