Last active
August 14, 2018 02:29
-
-
Save CMCDragonkai/9cf9d265042b21e2682c394eab1105d2 to your computer and use it in GitHub Desktop.
Created and Updated Timestamps on SQL Databases #sql #mysql #postgresql
This file contains 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
// from MySQL 5.6.5+ | |
CREATE TABLE test ( | |
id INT UNSIGNED NOT NULL AUTO_INCREMENT, | |
created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, | |
updated DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, | |
PRIMARY KEY (id) | |
); | |
// beware of the timezone you're storing the datetime at |
This file contains 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
CREATE TABLE test ( | |
id SERIAL NOT NULL PRIMARY KEY, | |
created TIMESTAMPTZ NOT NULL DEFAULT NOW(), | |
updated TIMESTAMPTZ NOT NULL DEFAULT NOW() | |
); | |
CREATE OR REPLACE FUNCTION set_updated() | |
RETURNS TRIGGER AS $$ | |
BEGIN | |
NEW.updated = NOW(); | |
RETURN NEW; | |
END; | |
$$ LANGUAGE plpgsql; | |
CREATE TRIGGER trigger_set_updated | |
BEFORE UPDATE ON test | |
FOR EACH ROW | |
EXECUTE PROCEDURE set_updated(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment