25

I don't know if this is possible, but I have a column named active in a table. Whenever the active column gets changed, I would like to reset the date in the date column, but ONLY if the active column gets changed.

If other columns are changed but not the active column, then the date would remain the same.

2

2 Answers 2

41

something like

DELIMITER //
 CREATE TRIGGER updtrigger BEFORE UPDATE ON mytable
     FOR EACH ROW
     BEGIN
     IF NEW.active <> OLD.active THEN
     SET NEW.date = '';     
     END IF;
     END
     //
Sign up to request clarification or add additional context in comments.

5 Comments

If I want to update the date to current date would the line change to SET NEW.date = CURDATE(); ?
if you want date yes, if you want date+time use NOW()
Had you set active = 1 while active was already 1 in the DB then wouldn't that be a change? I guess technically it would, because you have set the column and in database terminology it's a column change. But NEW.active is not OLD.active gives you only if NEW and OLD had different values! What will you do in that case? @HaimEvgi
Isn't it better to use <=> instead of <> ?
@stack yes, although not literally, <=> means "equal to, where null is treated like a value that can be compared", so you'd need to change to not NEW.active <=> OLD.active
19

Ran into an issue with the IF test in the #2 example. When one of the values is null the <> test returns null. This leads to the test not getting met and the action of the trigger will not get run even though the one value does not equal null at all. To fix this I came up with this test that uses <=> (NULL-safe equal). Hope this helps someone out.

DELIMITER $$
DROP TRIGGER IF EXISTS updtrigger ;
$$
CREATE TRIGGER updtrigger  AFTER UPDATE
    ON yourTable FOR EACH ROW
BEGIN
    IF ((NEW.active <=> OLD.active) = 0)  THEN
     SET NEW.date = '';     
     END IF;
$$

5 Comments

You can simply use the NOT operator instead of comparing to zero, as in the following answer: stackoverflow.com/a/24041832/1419007. Otherwise, good answer.
Shouldn't this have END before the final $$?
@Johnglassman - why not use BEFORE instead of AFTER?
@ValterEkholm Was a long time ago, but I suspect that my own use case was an after trigger and it was not the relevant aspect of my post. I would bet the test behaves the same way regardless of the trigger action.
@JohnGlassman Ok, you seem to remember quite well after all years. I have a memory of testing "after" and when it didn't work, I posted this/that comment, but it did work (in my use case, as I remeber) when using "before". Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.