CodeBlanks Logo Icon CodeBlanks

INSERT trigger

Fire after an INSERT.

INSERT trigger

An INSERT trigger fires when a new row is added. NEW accesses the new values.

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

This query logs the new product.

The trigger log_new is created.

INSERT trigger — details

In an INSERT trigger NEW is used. There is no OLD because there was no prior row.

For example, you can write NEW.name of the inserted product into a log table or fill NEW.created_at automatically.

Practice INSERT trigger

Write an AFTER INSERT trigger: log NEW.id and NEW.name.

Starter code

query.sql
-- insert trigger
CREATE TRIGGER log_new

Sample solution

query.sql
CREATE TRIGGER log_new
AFTER INSERT ON products
FOR EACH ROW
BEGIN
  INSERT INTO log VALUES (NEW.id, 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 INSERT trigger: match the terms

Term Meaning
INSERT insert
NEW new value
AFTER after
log record

2 Add NEW

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

Explanation: NEW gives access to the new values of the inserted or updated row.

3 What is used in an INSERT trigger?

  • OLD
  • BOTH
  • NEW Correct answer
  • NONE

Explanation: An INSERT trigger uses NEW.

All lessons in Advanced