-
-
Save wallleap/1cc4b95c97f121ea971996d55a26b782 to your computer and use it in GitHub Desktop.
Saved from https://stackoverflow.com/questions/50603953/how-to-add-created-at-and-updated-at-columns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| According to the reference manual* you can use the DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses in column definitions: | |
| With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP, the column has the current timestamp for its default value and is automatically updated to the current timestamp. | |
| whereas: | |
| With a DEFAULT clause but no ON UPDATE CURRENT_TIMESTAMP clause, the column has the given default value and is not automatically updated to the current timestamp. | |
| So, for example, you could use: | |
| ```sh | |
| CREATE TABLE t1 ( | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP , | |
| updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP | |
| ); | |
| ``` | |
| To add the columns to an already existing table you can use: | |
| ```sh | |
| ALTER TABLE t1 | |
| ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | |
| ADD COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; | |
| ``` | |
| > Note: Link provided refers to MySQL 8.0. The syntax is the same for previous versions as well. There is some difference though for versions prior to 5.6.5. Just quoting from the manual again: | |
| > | |
| > As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically initializated and updated to the current date and time (that is, the current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and for at most one TIMESTAMP column per table. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment