Before Trigger Cancel Write Return Null
A BEFORE row trigger that returns NULL silently cancels the write: the row never lands, no error is raised, and the statement simply affects fewer rows.
Code
-- BEFORE 行级触发器返回 NULL 会静默取消(cancel)这次写入:
-- 行不落表、不报错,语句只影响剩余的行
CREATE TEMP TABLE comments (
comment_id bigint GENERATED ALWAYS AS IDENTITY,
body text NOT NULL,
author_role text NOT NULL
);
CREATE OR REPLACE FUNCTION block_banned_author() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.author_role = 'banned' THEN
RETURN NULL; -- 取消这次 INSERT
END IF;
RETURN NEW; -- 放行;也可以先修改 NEW 再返回
END;
$$;
CREATE TRIGGER comments_block_banned
BEFORE INSERT ON comments
FOR EACH ROW EXECUTE FUNCTION block_banned_author();
INSERT INTO comments (body, author_role) VALUES ('hello', 'member');
INSERT INTO comments (body, author_role) VALUES ('spam', 'banned');
SELECT comment_id, body FROM comments;How it works
What runs here is SELECT / INSERT / CREATE — comments are the objects involved.
comments is created inside this same file as session-local temp tables — nothing has to be set up in advance, and it disappears when the session closes.
Mechanically, the statements are built from: NOT NULL qualifiers on the required columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Putting it to use
It carries its own setup: the session-local tables in play (comments) come from the file’s statements — run the entire file against a disposable database.
Core lines
CREATE OR REPLACE FUNCTION block_banned_author() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.author_role = 'banned' THEN
RETURN NULL; -- 取消这次 INSERT
END IF;
RETURN NEW; -- 放行;也可以先修改 NEW 再返回
END;
$$;
CREATE TRIGGER comments_block_banned
BEFORE INSERT ON comments
FOR EACH ROW EXECUTE FUNCTION block_banned_author();
CREATE TEMP TABLE comments (
comment_id bigint GENERATED ALWAYS AS IDENTITY,
body text NOT NULL,
author_role text NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which tables does the SQL touch?
- The references are `comments`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.