×

sql · level 3 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A trigger can stop a bad change with .

Some rules are too clever for a CHECK, such as a price never rising by more than half in one go. A BEFORE trigger runs before the change happens, so it can compare OLD with NEW and refuse.

A WHEN condition after the table name makes the trigger fire only for bad changes. Inside, SELECT RAISE(ABORT, 'message') stops and undoes the statement, and your message becomes the error. RAISE(IGNORE) skips the bad row quietly instead.

Write messages that say plainly what went wrong.

CREATE TRIGGER fair_price BEFORE UPDATE OF price ON books
WHEN NEW.price > OLD.price * 1.5
BEGIN
  SELECT RAISE(ABORT, 'Price rise too big');
END;

UPDATE books SET price = 10 WHERE id = 1;
SELECT title, price FROM books WHERE id = 1;

From 8 to 10 is a fair rise, so the trigger stays quiet and the update goes through.