Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active August 14, 2018 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/9cf9d265042b21e2682c394eab1105d2 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/9cf9d265042b21e2682c394eab1105d2 to your computer and use it in GitHub Desktop.
Created and Updated Timestamps on SQL Databases #sql #mysql #postgresql
// 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
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