MySQL BEFORE DELETE Trigger
Last Updated :
07 Aug, 2024
MySQL BEFORE DELETE
trigger is a powerful tool that automatically performs specific actions before an DELETE
operation is executed on a table. This feature allows us to handle tasks such as logging deleted records, enforcing business rules or validating data before it is removed from the database.
In this article, we will How the BEFORE DELETE trigger in MySQL works, including its syntax, usage, and practical examples.
MySQL BEFORE DELETE Trigger
- A MySQL
BEFORE DELETE
trigger is a special type of trigger that automatically executes a specified set of operations before a DELETE
operation is carried out on a table.
- This allows us to perform actions such as logging changes, validating data, or enforcing business rules before the actual deletion of records occurs.
Syntax
A BEFORE DELETE trigger is created using the CREATE TRIGGER statement.
The syntax is as follows:
CREATE TRIGGER trigger_name
BEFORE DELETE
ON table_name
FOR EACH ROW
BEGIN
-- trigger logic
END;
Explanation:
- trigger_name: The name of the trigger.
- table_name: The name of the table on which the trigger is applied.
- BEGIN ... END;: The block where the trigger logic is written.
Example 1: Logging Deleted Records
Lets, we have a table named employees and we want to log the details of any deleted employee into another table deleted_employees.
/* creating table for employess */
CREATE TABLE emp(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
position VARCHAR(100)
);
/* creating table from deleted employees */
CREATE TABLE del_emp (
id INT,
name VARCHAR(100),
position VARCHAR(100),
deleted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Creating trigger:
CREATE TRIGGER trig_del_emp
BEFORE DELETE ON employees
FOR EACH ROW
BEGIN
INSERT INTO del_emp (id, name, position)
VALUES (OLD.id, OLD.name, OLD.position);
END;
Explanation:
- When an employee record is deleted from the employees table, the trigger trig_del_employee inserts the deleted record's details into the deleted_employees table.
- The OLD keyword enable you to access columns in the rows affected by the delete trigger.
See all data of the tables,
select * from emp;
select * from del_emp;
Output:
fetching all the dataNow lets delete some data,
delete from emp where id<4;
Let's verify both the tables.
select * from emp;
select * from del_emp;
Output:
fetch data after deleteExample 2: Preventing Deletion of Certain Records
Now we want to prevent the deletion of those employees who hold the position 'Manager'.
Creating trigger:
CREATE TRIGGER trig_del_prev
BEFORE DELETE ON employees
FOR EACH ROW
BEGIN
IF OLD.position = 'Manager' THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Managers cannot be deleted.';
END IF;
END;
Explanation:
If an attempt is made to delete an employee with the position 'Manager', the trigger will raise an error and prevent the deletion.
lets try to delete that employee who is manager.
delete from emp where name='Bob';
Output:
deleteding dataConclusion
The BEFORE DELETE
trigger in MySQL offers a versatile way to control and monitor data deletion activities. By using this trigger, you can ensure that important data is preserved in audit logs or prevent certain deletions based on business rules. Mastering the use of BEFORE DELETE
triggers can significantly enhance data integrity and provide greater control over database operations.
Similar Reads
MySQL AFTER DELETE Trigger
In MySQL, triggers are a concept where SQL developers can define automatic actions to occur in response to specific changes in a database table. An AFTER DELETE trigger, for instance, is invoked automatically after a row is deleted from a table, allowing developers to perform additional operations s
4 min read
MySQL Before Insert Trigger
MySQL BEFORE INSERT triggers are essential tools for maintaining data quality and enforcing business rules at the database level. These triggers automatically execute a series of SQL statements before a new row is inserted into a table, allowing for data validation, modification, and enhancement.An
5 min read
MySQL Create Trigger
Database triggers are specialized procedures that automatically respond to certain events on a table or view. These events include actions such as INSERT, UPDATE, or DELETE. Triggers can be used to enforce complex business rules, maintain audit trails, or synchronize data across tables. In MySQL, tr
4 min read
MySQL BEFORE UPDATE Trigger
The MySQL triggers are a powerful feature that allows the execute a set of SQL statements automatically in response to certain events on a table. One type of trigger is the BEFORE UPDATE trigger which is invoked before an update operation is performed on the table. This article provides a complete o
4 min read
MySQL After Insert Trigger
An "AFTER INSERT" trigger in MySQL automatically executes specified actions after a new row is inserted into a table. It is used to perform tasks such as updating related tables, logging changes or performing calculations, ensuring immediate and consistent data processing.In this article, We will le
4 min read
MySQL DROP Trigger
In MySQL, triggers automatically perform actions when events like INSERT, UPDATE, or DELETE occur on a table However, there are situations where a trigger may not be necessary and its logic may need to be updated. In such cases, MySQL provides the DROP TRIGGER statement to delete an existing trigger
4 min read
PL/SQL Enable Triggers
In PL/SQL, triggers are special stored procedures that automatically execute in response to certain events on a particular table or view. These triggers can be used to enforce complex business rules, maintain integrity constraints, or track changes in the database. However, triggers can be enabled o
6 min read
PL/SQL Drop Triggers
In database management, triggers play an important role in maintaining data integrity and enforcing business rules automatically. However, there may be situations where we need to remove an existing trigger from a database. This process is accomplished using the DROP TRIGGER statement in PL/SQL.In t
4 min read
MySQL AFTER UPDATE Trigger
Triggers in MySQL are special stored programs that are automatically executed when a specific event occurs on the table such as an INSERT, UPDATE, or DELETE. An AFTER UPDATE trigger is a type of trigger that executes after an UPDATE statement is performed on the table. This article provides a comple
4 min read
PL/SQL Disable Triggers
Triggers in PL/SQL are designed to automatically perform actions in response to specific events on a table, such as INSERT, UPDATE, or DELETE. However, there are times when you may need to temporarily disable these triggers, To perform updates or to speed up large data imports. In this article, We w
4 min read