CodeBlanks Logo Icon CodeBlanks

BEFORE and AFTER

Learn the timing difference.

BEFORE and AFTER

BEFORE runs before the event, AFTER after. BEFORE for validation, AFTER for logging.

CREATE TRIGGER check_balance
BEFORE UPDATE ON accounts
FOR EACH ROW
BEGIN
  IF NEW.balance < 0 THEN
    SIGNAL SQLSTATE '45000';
  END IF;
END;

This query checks before the update.

The trigger check_balance is created.

BEFORE and AFTER — details

A BEFORE trigger can modify data or stop the operation. AFTER only reads.

For example, BEFORE UPDATE can reject a negative balance; AFTER UPDATE is suited to adding a log entry once the change is written.

Practice BEFORE and AFTER

Write a BEFORE UPDATE trigger: block negative balance.

Starter code

query.sql
-- before trigger
CREATE TRIGGER check_balance

Sample solution

query.sql
CREATE TRIGGER check_balance
BEFORE UPDATE ON accounts
FOR EACH ROW
BEGIN
  IF NEW.balance < 0 THEN
    SIGNAL SQLSTATE '45000';
  END IF;
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 Add BEFORE

Question
CREATE TRIGGER check_balance
____ UPDATE ON accounts
Answer
CREATE TRIGGER check_balance
BEFORE UPDATE ON accounts

Explanation: A BEFORE UPDATE trigger runs before the update is written, so it can block an invalid value.

2 Which trigger for validation?

  • BEFORE Correct answer
  • AFTER
  • INSTEAD
  • DURING

Explanation: A BEFORE trigger is for validation.

3 BEFORE and AFTER: match the terms

Term Meaning
BEFORE before
AFTER after
validation check
logging record

All lessons in Advanced