CodeBlanks Logo Icon CodeBlanks

UPDATE trigger

Fire after an UPDATE.

UPDATE trigger

An UPDATE trigger fires when a row is updated. Both OLD and NEW are accessible.

CREATE TRIGGER log_change
AFTER UPDATE ON products
FOR EACH ROW
BEGIN
  INSERT INTO log VALUES (OLD.name, NEW.name);
END;

This query logs old and new name.

The trigger log_change is created.

UPDATE trigger — details

In an UPDATE trigger both OLD and NEW are used. Ideal for tracking changes.

For example, if OLD.price differs from NEW.price you record the price change in a history table with both values.

Practice UPDATE trigger

Write an AFTER UPDATE trigger: log OLD.name and NEW.name.

Starter code

query.sql
-- update trigger
CREATE TRIGGER log_change

Sample solution

query.sql
CREATE TRIGGER log_change
AFTER UPDATE ON products
FOR EACH ROW
BEGIN
  INSERT INTO log VALUES (OLD.name, NEW.name);
END

Expected output

Trigger oluşturuldu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is accessible in an UPDATE trigger?

  • Only NEW
  • OLD and NEW Correct answer
  • NONE
  • Only OLD

Explanation: Both OLD and NEW are accessible in an UPDATE trigger.

2 Add OLD

Question
  INSERT INTO log VALUES (____.name, NEW.name);
Answer
  INSERT INTO log VALUES (OLD.name, NEW.name);

Explanation: OLD gives the row's value before the change, NEW the value after it.

3 UPDATE trigger: match the terms

Term Meaning
UPDATE update
OLD old value
NEW new value
change difference

All lessons in Advanced