Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Is there a way to automatically set datetime field to record creation timestamp?

I know there is TIMESTAMP data type that automatically updates to timestamp value when a record is updated, and I already have such column.

Besides that I'd like to have a column that automatically populates to NOW() (or CURRENT_TIMESTAMP) and never changes, but MySQL DEFAULT doesn't appear to support function calls.

Please post only pure MySQL answers. I know how to do it at application level.

EDIT: If there's no such feature - I'd appreciate to hear that.

EDIT2: MySQL version is 5.0.32

like image 795
tishma Avatar asked Dec 17 '22 19:12

tishma


1 Answers

Use a trigger to set the default.

DELIMITER |

CREATE
    TRIGGER trigger_name BEFORE INSERT ON tbl_name FOR EACH ROW 
BEGIN
    SET NEW.colname = NOW();
END; 

|

Try this one, including the delimiter.

like image 153
Frank Heikens Avatar answered Jan 13 '23 22:01

Frank Heikens