CodeBlanks Logo Icon CodeBlanks

What is a trigger?

Learn routines that fire on an event.

What is a trigger?

A trigger is code that runs automatically on an event. Fires on INSERT, UPDATE or DELETE.

CREATE TRIGGER log_insert
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
  INSERT INTO log VALUES (NEW.id);
END;

This query logs on every insert.

The trigger log_insert is created.

What is a trigger? — details

A trigger runs automatically on table events. It is not called manually.

When an INSERT, UPDATE or DELETE happens, the database runs the trigger itself; application code can't forget it, which makes triggers reliable for enforcing rules.

Practice What is a trigger?

Create a log_insert trigger: log on AFTER INSERT.

Starter code

query.sql
-- create trigger
CREATE

Sample solution

query.sql
CREATE TRIGGER log_insert
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
  INSERT INTO log VALUES (NEW.id);
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 When does a trigger run?

  • Only on CREATE
  • When called manually
  • Never
  • Automatically, on an event Correct answer

Explanation: A trigger runs automatically on an event.

2 Add TRIGGER

Question
CREATE ____ log_insert
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
  INSERT INTO log VALUES (NEW.id);
END;
Answer
CREATE TRIGGER log_insert
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
  INSERT INTO log VALUES (NEW.id);
END;

Explanation: TRIGGER is the right answer.

3 What is a trigger: match the terms

Term Meaning
trigger trigger
AFTER after
BEFORE before
INSERT insert

All lessons in Advanced