AI Hints
PostgreSQL · Lesson 76 of 120

Triggers

Run code on changes.

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

Every time a book's price changes, the updated at time should change too. Nobody should have to remember. A trigger runs a function automatically, whenever a row changes.

  • Price changes
  • Stamp the time
  • Automatically

Keep updated_at fresh

We add an updated at column. The trigger function sets it to now, on the new row. The trigger calls it before every update on books. Run it. The update stamps the time by itself.

query.sqlsql
ALTER TABLE books ADD COLUMN updated_at timestamptz;

CREATE FUNCTION touch() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  NEW.updated_at := now();
  RETURN NEW;
END $$;

CREATE TRIGGER books_touch BEFORE UPDATE ON books
FOR EACH ROW EXECUTE FUNCTION touch();

UPDATE books SET price = 15.49 WHERE book_id = 1;
SELECT title, price, updated_at IS NOT NULL AS stamped FROM books WHERE book_id = 1;
Output
ALTER TABLE
CREATE FUNCTION
CREATE TRIGGER
UPDATE 1
       title        | price | stamped
--------------------+-------+---------
 The Silent Orchard | 15.49 | t
(1 row)

Trigger basics

Before triggers can change the new row. After triggers see the final result, good for logging. For each row runs once per row, and for each statement once per query. New and old hold the row after and before.

keyvalue
BEFOREchange NEW
AFTERlog, notify
FOR EACH ROWper row
NEW / OLDafter / before

Summary

Triggers run a function automatically when rows change. Next, an audit log built with a trigger.

Key takeaways
  • CREATE TRIGGER
  • BEFORE UPDATE
  • NEW
Next up: An Audit Log Trigger — who changed what