0

I have created a BEFORE INSERT trigger on a Mysql table. I want to create a default value behavior for a date field in mySQL 5.4. This means I want to use the value from the trigger if no value is provided for this field at the insert.

CREATE TRIGGER `be_table1` 
BEFORE INSERT ON `table1` FOR EACH ROW SET NEW.`date_joined` = NOW();

This works so far. But if I now insert data into my table like this ...

INSERT INTO table1 (date_joined, productname) VALUES ('2001-02-10', 'hello world');

... not '2001-02-10' is inserted, but the current date.

As far as I understood the BEFORE INSERT trigger, it pre-populates the field and should be overwritten by the insert statement. Am I wrong?

3
  • 1
    MySQL 5.4 is downright ancient at this point. If you can upgrade to 5.7 or 8.0 you'll see considerable performance benefits. Commented Feb 10, 2021 at 22:40
  • Can you add a WHERE NEW.date_joined IS NULL clause? Commented Feb 10, 2021 at 22:40
  • Thanks. Where can I add this clause? I get a syntax error if I put it right behind Now() Commented Feb 10, 2021 at 22:43

1 Answer 1

4

You can modify the values to be inserted in the before insert trigger, not pre-populate it!

You can use coalesce() function to override the NEW value only if it is null:

...
SET NEW.`date_joined` = COALESCE(NEW.`date_joined`, NOW());
Sign up to request clarification or add additional context in comments.

1 Comment

In MySQL this is also known as IFNULL(), though COALESCE() is more in line with the SQL standard.

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.