Statement-Level Triggers With Transition Tables

Use statement-level triggers with transition tables to audit an entire multi-row UPDATE once, comparing old and new rows in a single insert.

SqlData Integrity

Code

snippet
-- transition tables:一次拿到整批受影响的行
CREATE TABLE IF NOT EXISTS price_changes (
  id bigserial PRIMARY KEY,
  product_id bigint NOT NULL,
  old_price numeric(10, 2),
  new_price numeric(10, 2),
  changed_at timestamptz DEFAULT now()
);

CREATE OR REPLACE FUNCTION log_price_changes()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  INSERT INTO price_changes (product_id, old_price, new_price)
  SELECT new_rows.id, old_rows.price, new_rows.price
  FROM new_rows
  JOIN old_rows USING (id)
  WHERE new_rows.price IS DISTINCT FROM old_rows.price;
  RETURN NULL;
END;
$$;

CREATE TRIGGER products_price_audit
AFTER UPDATE ON products
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows
FOR EACH STATEMENT
EXECUTE FUNCTION log_price_changes();

-- 一条 UPDATE 影响多行,但触发器只执行一次
UPDATE products SET price = price * 1.1 WHERE category = 'tools';

What the code does

Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with price_changes, new_rows, old_rows, old_rows.price and on among the objects involved.

Mechanically, the statements are built from: one JOIN combining rows across tables; a WHERE clause narrowing which rows one statement affects; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Applying it

Run the statement against the price_changes table.

Statements that matter

CREATE OR REPLACE FUNCTION log_price_changes()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  INSERT INTO price_changes (product_id, old_price, new_price)
  SELECT new_rows.id, old_rows.price, new_rows.price
  FROM new_rows
  JOIN old_rows USING (id)
  WHERE new_rows.price IS DISTINCT FROM old_rows.price;
CREATE TRIGGER products_price_audit
AFTER UPDATE ON products
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows
FOR EACH STATEMENT
EXECUTE FUNCTION log_price_changes();
UPDATE products SET price = price * 1.1 WHERE category = 'tools';

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`price_changes`, `new_rows`, `old_rows`, `old_rows.price`, `on` — joined via one JOIN clause.