Selected topic

BEFORE Trigger

Triggers

Prefer practical output? Use related tools below while reading.

In SQL, a Trigger is a stored procedure that automatically executes in response to certain events on a table. These events can be insertions, deletions, or modifications (updates) made to the data in the table.

Here are some key points about triggers:

### BEFORE Trigger

A BEFORE trigger is a type of trigger that runs before an action (insertion, deletion, update) takes place on a table. This means that the triggering event (the event that causes the trigger to fire) occurs after the execution of the BEFORE trigger.

Example


Let's consider an example where we have a Customers table and we want to insert data into it but also perform some validation before actually inserting the record. We can use a BEFORE INSERT trigger for this purpose.

sql
CREATE TABLE Customers (
  CustID INT,
  Name VARCHAR(255),
  Email VARCHAR(255)
);

CREATE TRIGGER ValidateEmail BEFORE INSERT ON Customers FOR EACH ROW BEGIN
IF NOT (NEW.Email RLIKE '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$') THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Invalid email format';
END IF;
END;

In this example, the ValidateEmail BEFORE INSERT trigger checks if the provided email address is in a valid format. If it's not, the trigger signals an error, preventing the insertion of the invalid data.

This way, we ensure that only properly formatted emails are inserted into our table, maintaining its integrity.