×

sql · level 3 · unit 6 · lesson 2

  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 runs by itself whenever a table changes.

A shop must keep a record of every price change, and people forget. A trigger never forgets. It is a set of statements the database runs by itself whenever a chosen change happens to a table.

runs once a price has changed. Its statements go between BEGIN and END. Inside, is the price before and is the price after.

An insert has only NEW, a delete has only OLD, and an update has both.

CREATE TABLE price_changes (book_id INTEGER, old_price INTEGER, new_price INTEGER);

CREATE TRIGGER log_price AFTER UPDATE OF price ON books
BEGIN
  INSERT INTO price_changes VALUES (OLD.id, OLD.price, NEW.price);
END;

UPDATE books SET price = 10 WHERE id = 1;
UPDATE books SET price = price - 1 WHERE id = 4;
SELECT * FROM price_changes ORDER BY book_id;

This BEGIN opens the trigger's body. It does not start a transaction.