i2tutorials

MySQL – Before Insert Trigger

MySQL – Before Insert Trigger

 

When an insert operation is performed in MySQL, the Before Insert Trigger is automatically invoked. We will learn how to create a before insert trigger in this article.

Syntax:

Here is the syntax for creating a BEFORE INSERT trigger in MySQL:

CREATE TRIGGER trigger_name   
BEFORE INSERT  
ON table_name FOR EACH ROW  
Trigger_body ;  

BEFORE INSERT trigger syntax parameter can be explained as follows:

Restrictions

Example

We have created a table named employees as follows:

CREATE TABLE employees(
name varchar(45) NOT NULL,
position varchar(35) NOT NULL,
working_date date,
working_hours varchar(10)
);

Next, we will insert some records into the employees table and then execute the SELECT statement to view the table data as follows:

INSERT INTO employees VALUES

('sai', 'Scientist', '2020-10-04', 12),
('mounika', 'Engineer', '2020-10-04', 10),
('lashmi', 'Actor', '2020-10-04', 13),
('charan', 'Doctor', '2020-10-04', 14),
('bhanu', 'Teacher', '2020-10-04', 12),
('venu', 'Business', '2020-10-04', 11);
('ravi', 'Scientist', '2020-10-08', 14);
('venkat', 'Actor', '2020-10-12', 14);

Next, we will create a BEFORE INSERT trigger using a CREATE TRIGGER statement. A trigger is invoked automatically that inserts the position= Doctor if someone attempts to insert the position= ‘Scientist’.

DELIMITER //
Create Trigger before_insert
BEFORE INSERT ON employees FOR EACH ROW
BEGIN
IF NEW.position = 'Scientist' THEN SET NEW.position = 'Doctor';
END IF;
END

In the event that the trigger is successfully created.

To invoke the trigger created above, we can use the following statements:

INSERT INTO employees VALUES
('ravi', 'Scientist', '2020-10-08', 14);

Following the execution of the above statement, we will receive the following output:

my

 

Exit mobile version