EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial MySQL UPDATE Trigger
Secondary Sidebar
MySQL Tutorial
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL?Table?Size
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL AB
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Interview Questions
    • MySQL Interview Questions

MySQL UPDATE Trigger

By Priya PedamkarPriya Pedamkar

MySQL UPDATE Trigger

Introduction to MySQL UPDATE Trigger

MySQL UPDATE_TRIGGER is one of the triggers that enable the update actions on the specified table. On a general note, a trigger can be defined as a set of instructions or steps which perform the intended change action automatically, on the specified table. The possible change actions can be INSERT, UPDATE, or DELETE. The concept of triggers is similar to stored procedures and the execution helps in saving time and effort in writing the queries. A trigger is an explicitly defined database object associated with a table and is defined using the ‘CREATE TRIGGER’ statement. We will discuss details of both CREATE TRIGGER and UPDATE TRIGGER statements in detail.

Syntax

Just like any other set of statements, TRIGGERS are also be created and dropped as per requirements. The CREATE trigger syntax is as below:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

CREATE
[DEFINER = user] TRIGGER trigger_name
trigger_time trigger_event
ON tbl_name FOR EACH ROW
[trigger_order] trigger_body

Explanation:

DEFINER: definer is the user who is entitled with the privilege to perfor the trigger operations.

trigger_name: trigger_name is the name of trigger instruction. This is a user-defined field.

trigger_time: trigger_time is the moment in which trigger is to be initiated. It is either BEFORE or AFTER indicating whether to perfor the trigger action before each row or after.

trigger_event: trigger_event is the change operation referred upon. INSERT, UPDATE or DELETE actions are used as triggers.

trigger_order: trigger order specifies if the trigger FOLLOWS or PRECEDES

trigger_body: trigger_body defines the trigger actions. If more than one statement is to be mentioned, it if preferred to use the BEGIN END block and also change the default delimiters.

So the syntax can be shown as:

DELIMITER $$
CREATE TRIGGER trigger_name
trigger_time trigger_event
ON table_name FOR EACH ROW
BEGIN
-- statements
END $$
DELIMITER;

How does UPDATE Trigger function works in MySQL

From the above discussion, we got to know there can be two UPDATE triggers, either BEFORE UPDATE or AFTER UPDATE. The difference in the working of these triggers is that the action is performed on each row before updating or after updating.

AFTER UPDATE trigger

Let us consider two tables to understand the UPDATE trigger in detail. The first table is InitialSales and the second table is SalesUpdates. Below is gives an idea of columns in the table.

Initial Sales table:

MySQL UPDATE Trigger1

sales update table is defined as:

Code:

CREATE TABLE SalesUpdates (
prodId INT AUTO_INCREMENT PRIMARY KEY,
sales_Id INT,
InitialQuantitiy INT,
UpdatedQuantity INT,
UpdatedOn TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Let’s define the Trigger as below:

Code:

DELIMITER $$
CREATE TRIGGER Updated_Sales_Data
AFTER UPDATE
ON InitialSales FOR EACH ROW
BEGIN
IF OLD.qty<>new.qty THEN
INSERT INTO SalesUpdates(sales_Id,InitialQuantity, UpdatedQuantity)
VALUES(old.prodId, old.qty, new.qty);
END IF;
END $$
DELIMITER;

Output:

MySQL UPDATE Trigger2

Explanation: The trigger name is Updated_Sales_Data. The trigger_event is “UPDATE” and trigger_time is “AFTER”. The trigger will act upon the table “InitialSales”. As per query, if any update is made to column “qty” in InitialSales table, a new entry will be added in the SalesUpdatetable, with old value and the new value of the “qty” column. Any updates made to the InitialSales table will automatically initiate the trigger. No need to explicitly execute the trigger every time.

To further check on the working of TRIGGER, let’s do two types of updates to the InitialSales table.

First, we will see updates made to the “qty” column of only one ‘prodId’.

Consider InitialSales table as below:

prodId

Code:

UPDATE InitialSales
SET qty = 500
WHERE prodId = 3;
Query will update the column ‘qty’ of prodId ‘3’, from ‘150’ to ‘500’.

Output:

rows matched

Let’s see both tables InitialSales and SalesUpdates:

InitialSales:

MySQL UPDATE Trigger5

SalesUpdates:

MySQL UPDATE Trigger6

If we look into this scenario, we can understand the below things:

  1. Update made to qty column in InitialSales table reflects properly
  2. SalesUpdates table has data only for the updated row of InitialSales table, which is a row of prodId = 3.
  3. The UPDATE TRIGGER was not explicitly called, but it automatically updated theSalesUpdate table.
  4. The SalesUpdates table holds old and new values of qty column

In the second scenario, let’s make an update to all three rows of the InitialSales table.

InitialSales:

MySQL UPDATE Trigger7

Code:

UPDATE initialSales
SET qty = CAST(qty * 1.5 AS UNSIGNED);

The query updates an increment to ‘qty’ column of all three rows in InitialSales table by 50%

Output:

unsigned

InitialSales:

MySQL UPDATE Trigger9

SalesUpdates:

The first row of the SalesUpdate table is the first update made to the InitialSales table ( by our first query). So, we can see that the SalesUpdate table holds the history of all updates made, along with a timestamp.

SalesUpdates

BEFORE UPDATE trigger

Thus we have clearly understood the AFTER UPDATE trigger. Let’s try and familiarise ourselves with the BEFORE UPDATE trigger now.

For the BEFORE UPDATE trigger, let us consider the tables as below:

InitialSales:

BEFORE UPDATE trigger

SalesUpdates:

Code:

CREATE TABLE SalesUpdates (
sales_Id INT AUTO_INCREMENT PRIMARY KEY,
prodId INT,
InitialQuantitiy INT,
UpdatedQuantity INT,
Updated On TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Let’s define the Trigger as below:

Code:

DELIMITER $$
CREATE TRIGGER Updated_Sales_Data
BEFORE UPDATE
ON InitialSales FOR EACH ROW
BEGIN
IF OLD.qty<>new.qtyTHEN
INSERT INTO SalesUpdates(sales_Id,InitialQuantity, UpdatedQuantity)
VALUES(old.prodId, old.qty, new.qty);
END IF;
END $$
DELIMITER;

Output:

create trigger

Explanation: The trigger name is Updated_Sales_Data. The trigger_event is “UPDATE” and trigger_time is “BEFORE”. The trigger will act upon the table “InitialSales”. As per query, if any update is made to column “qty”in InitialSales table, a new entry will be added in the SalesUpdatetable, with old value and new value of “qty” column. Any updates made to the InitialSales table will automatically initiate the trigger. No need to explicitly execute the trigger every time.

We have our InitialSales table as below:

MySQL UPDATE Trigger13

And SalesUpdate table as below:

MySQL UPDATE Trigger14

Let’s execute a query to make an update in the qty column in the InitialSales table.

Code:

UPDATE InitialSales
SET qty = 500
WHERE prodId = 3;

Output:

MySQL UPDATE Trigger15

InitialSales table: the qty value in this table is updated to ‘1000’ for prodId = 1 from value ‘600’.

qty value

SalesUpdates table: the initial value and updated value of qty column are displayed, along with the update_timestamp.

Update Timestamp

In general, we can say, the BEFORE UPDATE trigger is used to make an update before it is committed to the database and AFTER UPDATE trigger updates after the database commit.

Conclusion

In this section, we discussed the UPDATE triggers. A trigger can either be a BEFORE trigger or an AFTER trigger. In the CREATE trigger statement, we define the trigger_event as UPDATE for UPDATE trigger, trigger_time as BEFORE or AFTER as per requirement, trigger name, trigger body, and the table on which trigger is to be performed. And for the UPDATE trigger, once the highlighted column faces any updates, the trigger is automatically called and the update table is updated.

Recommended Articles

This is a guide to MySQL UPDATE Trigger. Here we discuss an introduction to MySQL UPDATE Trigger, syntax and how does it work with query examples. You can also go through our other related articles to learn more –

  1. Triggers in SQL
  2. MySQL Trigger
  3. Oracle Triggers
  4. Cursor in MySQL
Popular Course in this category
MySQL Training Program (12 Courses, 10 Projects)
  12 Online Courses |  10 Hands-on Projects |  92+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (17 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more