Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire a trigger after the update of specific columns in MySQL

In MySQL, I want to fire a trigger after the update of specific columns.

I know how to do it in Oracle and DB2:

CREATE  TRIGGER  myTrigger AFTER UPDATE of myColumn1,myColumn2 ... ON myTable FOR EACH ROW BEGIN .... END 

How to do that with MySQL?

like image 529
senior Avatar asked Oct 03 '13 07:10

senior


People also ask

How do you execute a trigger only when a specific column is updated in MySQL?

In SQL Server, you can create DML triggers that execute code only when a specific column is updated. The trigger still fires, but you can test whether or not a specific column was updated, and then run code only if that column was updated. You can do this by using the UPDATE() function inside your trigger.

How do I create a trigger in SQL after update?

By default, triggers will be created in the schema you are currently working in. trigger_name: This is the name of the trigger which you want to create. table_name: This is the name of the table to which the trigger will be applied. SQL statements: SQL statements form the body of the trigger.

How do I know which column is updated in a trigger?

Using a SQL Server trigger to check if a column is updated, there are two ways this can be done; one is to use the function update(<col name>) and the other is to use columns_updated().

Can we update a trigger in MySQL?

Restrictions. We can access the OLD rows but cannot update them. We can access the NEW rows but cannot update them. We cannot create an AFTER UPDATE trigger on a VIEW.


2 Answers

You can't trigger on a particular column update in SQL. It is applied on a row.

You can put your condition for columm in your trigger with an IF statement, as below:

DELIMITER // CREATE TRIGGER myTrigger AFTER UPDATE ON myTable FOR EACH ROW BEGIN    IF !(NEW.column1 <=> OLD.column1) THEN       --type your statements here    END IF; END;// DELIMITER ; 
like image 103
Nitu Bansal Avatar answered Oct 13 '22 23:10

Nitu Bansal


You can't specify only to fire on specific column changes. But for a record change on a table you can do

delimiter | CREATE  TRIGGER  myTrigger AFTER UPDATE ON myTable FOR EACH ROW BEGIN    ... END | delimiter ; 

In your trigger you can refer to old and new content of a column like this

if NEW.column1 <> OLD.column1 ... 
like image 26
juergen d Avatar answered Oct 13 '22 22:10

juergen d