Fire trigger after the DELETE operation is executed in MySQL


Use AFTER DELETE to fire trigger after the DELETE operation is executed. Following is the syntax −

DELIMITER //
   CREATE TRIGGER yourTriggerName
      AFTER DELETE
      ON yourTableName FOR EACH ROW
      BEGIN
      yourStatement1,
      .
      .
      N
   END;
   //

Let us first create a table −

mysql> create table DemoTable(Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,FirstName varchar(100));
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1  | John      |
| 2  | Mike      |
+----+-----------+
2 rows in set (0.00 sec)

Following is the query to create trigger and use AFTER DELETE as well −

mysql> DELIMITER //
mysql> CREATE TRIGGER history_of_Table
   AFTER DELETE
      ON DemoTable FOR EACH ROW
   BEGIN
      SELECT USER() INTO @userName;
      SELECT NOW() INTO @deleteDatetime;
   END; //
Query OK, 0 rows affected (0.18 sec)
mysql> DELIMITER ;

To check the trigger is working or not, delete first record from the table −

mysql> delete from DemoTable where Id=1;
Query OK, 1 row affected (0.26 sec)

Above, we have deleted first record from the table. This means trigger must be active after DELETE command is used −

mysql> select @userName;

This will produce the following output −

+----------------+
| @userName      |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It displays the current time whenever trigger works −

mysql> select @deleteDatetime;

This will produce the following output −

+---------------------+
| @deleteDatetime     |
+---------------------+
| 2019-07-09 21:06:31 |
+---------------------+
1 row in set (0.00 sec)

Updated on: 22-Aug-2019

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements