MySQL auto-store datetime for each row

SqlMysqlDatetimeAudit

Sql Problem Overview


In MySQL, I'm sick of adding the columns dt_created and dt_modified (which are date time stamps for creation and last modified respectively) to all the tables I have in my database.

Every time I INSERT or UPDATE the database, I will have to use the NOW() keyword. This is going all over my persistence.

Is there any efficient alternative where MySQL can automatically store at least the datatime of the row that is inserted and let me retrieve it?

Sql Solutions


Solution 1 - Sql

You can use DEFAULT constraints to set the timestamp:

ALTER TABLE
 MODIFY dt_created datetime DEFAULT CURRENT_TIMESTAMP

ALTER TABLE
 MODIFY dt_modified datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Then you wouldn't have to specify NOW() in your INSERT/UPDATE statements.

Reference: TIMESTAMP properties

Solution 2 - Sql

If you're using phpmyadmin you can do this by :

enter image description here

Solution 3 - Sql

ALTER TABLE  `tablename` CHANGE  `dt`  `dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

should be the correct code.

Solution 4 - Sql

Well, you can't have both:

mysql doc: > It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.

Sad, isn't it?

You could however use null instead of now() following this tip

Solution 5 - Sql

Similar question was asked here "Timestamp for MySQL" the timestamp field will update every time it is accessed. You might also consider a Trigger placed on the table in question to automatically populate those fields for you. Depending on the environment some shops/businesses do not like the use of triggers and so you might have to find alternate work arounds.

Solution 6 - Sql

In phpmyadmin you can set enter image description here

OR use this query

ALTER TABLE  `tablename`
    CHANGE  `dt_created`  `dt_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Solution 7 - Sql

could be set as default an on update of rows

ALTER TABLE `tablename` CHANGE `dt` `dt` TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmaurisView Question on Stackoverflow
Solution 1 - SqlOMG PoniesView Answer on Stackoverflow
Solution 2 - SqlOuadieView Answer on Stackoverflow
Solution 3 - SqlKim StacksView Answer on Stackoverflow
Solution 4 - SqlggdView Answer on Stackoverflow
Solution 5 - SqlGrayWizardxView Answer on Stackoverflow
Solution 6 - Sqluser3110005View Answer on Stackoverflow
Solution 7 - SqlJan MarkView Answer on Stackoverflow