Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
MySQL BEFORE UPDATE Trigger
Next article icon

MySQL BEFORE UPDATE Trigger

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 overview of the BEFORE UPDATE trigger including its syntax, use cases, and practical examples.

Introduction to MySQL Triggers

The MySQL triggers are database objects that are automatically executed or fired when certain events occur. These events can be INSERT, UPDATE, or DELETE operations on the table. The Triggers help enforce business rules, validate data, and maintain data integrity.

Understanding BEFORE UPDATE Triggers

The BEFORE UPDATE trigger is executed before an update operation is performed on the table. This type of trigger can be used to validate or modify data before it is updated in the database. For example, we might use a BEFORE UPDATE trigger to ensure that certain business rules are enforced or to automatically update a timestamp column.

Syntax of BEFORE UPDATE Trigger

The basic syntax for creating a BEFORE UPDATE trigger in MySQL is as follows:

CREATE TRIGGER trigger_name

BEFORE UPDATE

ON table_name

FOR EACH ROW

BEGIN

-- Trigger logic here

END;

  • trigger_name: The name of the trigger.
  • table_name: The name of the table on which the trigger is to be created.
  • The BEGIN...END block contains the SQL statements that make up the trigger logic.

Creating a BEFORE UPDATE Trigger

Let's create a simple example to show how to create a BEFORE UPDATE trigger. Suppose we have a table called the employees with the following structure:

CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
position VARCHAR(100),
salary DECIMAL(10, 2),
last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

We want to create a BEFORE UPDATE trigger that updates the last_modified column with current timestamp whenever an employee's information is updated.

DELIMITER //

CREATE TRIGGER before_employee_update
BEFORE UPDATE
ON employees
FOR EACH ROW
BEGIN
SET NEW.last_modified = CURRENT_TIMESTAMP;
END;
//

DELIMITER ;

In this example:

  • The trigger is named before_employee_update.
  • The trigger is associated with employees table.
  • The trigger logic sets the last_modified column to current timestamp before the update operation.

Insert Sample Data into employees Table

INSERT INTO employees (name, position, salary) VALUES ('John Doe', 'Developer', 70000.00);
INSERT INTO employees (name, position, salary) VALUES ('Jane Smith', 'Manager', 80000.00);

Update Data to Trigger the BEFORE UPDATE Trigger

The Update an employee's details to the activate the trigger:

UPDATE employees SET salary = 75000.00 WHERE name = 'John Doe';

Check the Contents of the employees Table

Retrieve the data from the employees table to see the effect of the trigger:

SELECT * FROM employees;

Output:

Output
Output

Example: Enforcing Business Rules

Suppose we have a table products with the columns id, name, price, and stock. We want to ensure that the price of the product cannot be negative. We can create a BEFORE UPDATE trigger to enforce this rule.

1. Create the products Table

CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10, 2),
stock INT
);

2. Create the BEFORE UPDATE Trigger

DELIMITER //
CREATE TRIGGER before_product_update
BEFORE UPDATE
ON products
FOR EACH ROW
BEGIN
IF NEW.price < 0 THEN
SET NEW.price = 0;
END IF;
END;
//
DELIMITER ;

3. Insert Sample Data

INSERT INTO products (name, price, stock) VALUES ('Product A', 100.00, 10);
INSERT INTO products (name, price, stock) VALUES ('Product B', 200.00, 20);

4. Update Data to Trigger the BEFORE UPDATE Trigger

Attempt to update the price of 'Product A' to a negative value:

UPDATE products SET price = -50 WHERE name = 'Product A';

5. Check the Results

Retrieve the data from the products table to see the effect of the trigger:

SELECT * FROM products;

Output:

Output
Output

Conclusion

The BEFORE UPDATE trigger in MySQL is a powerful tool for enforcing business rules, validating data, and maintaining data integrity. By understanding how to create and use these triggers we can enhance the functionality and reliability of the database applications. This article has provided an overview of the BEFORE UPDATE trigger its syntax and practical examples.


Next Article
MySQL BEFORE UPDATE Trigger

G

gururaj69bn
Improve
Article Tags :
  • Databases
  • MySQL

Similar Reads

    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
    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 BEFORE DELETE Trigger
    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
    3 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 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences