AI Hints
PostgreSQL · Lesson 77 of 120

An Audit Log Trigger

Who changed what.

⏱ 2 min read▶ Video at 1:09:14🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Price changes need an audit trail. Who changed it, when, and from what to what. An after update trigger can write every change into a log table.

  • Who?
  • When?
  • Old and new

Log every price change

The log table stores the book, old price, new price, user and time. The trigger function inserts a row using old and new. When restricts it to real price changes. Run it. Two updates, two log rows.

query.sqlsql
CREATE TABLE price_log (book_id int, old numeric, new numeric,
  changed_by text DEFAULT current_user, changed_at timestamptz DEFAULT now());

CREATE FUNCTION log_price() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO price_log (book_id, old, new) VALUES (OLD.book_id, OLD.price, NEW.price);
  RETURN NULL;
END $$;

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

UPDATE books SET price = price + 1 WHERE book_id IN (1, 2);
SELECT book_id, old, new, changed_by FROM price_log ORDER BY book_id;
Output
CREATE TABLE
CREATE FUNCTION
CREATE TRIGGER
UPDATE 2
 book_id |  old  |  new  | changed_by
---------+-------+-------+------------
       1 | 14.99 | 15.99 | postgres
       2 | 12.99 | 13.99 | postgres
(2 rows)

Audit tips

After triggers see the final values. Store the user and time. Keep the log table append only. And for full history of every column, a generic trigger can store old and new as JSONB.

keyvalue
AFTERfinal values
current_userwho
Append onlynever edit logs
to_jsonb(OLD)whole rows

Summary

An after update trigger can record every change into an audit table. Next, practise with a stock trigger.

Key takeaways
  • AFTER UPDATE
  • OLD / NEW
  • Audit log
Next up: Practice: Stock Trigger — orders reduce stock