Skip to content

Instantly share code, notes, and snippets.

@incyclum
Last active May 1, 2018 07:28
Show Gist options
  • Save incyclum/a19bcf9d2b405b38a5f509fd1a8fed66 to your computer and use it in GitHub Desktop.
Save incyclum/a19bcf9d2b405b38a5f509fd1a8fed66 to your computer and use it in GitHub Desktop.
PostgreSQL - Automatically update a timestamp
CREATE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ language 'plpgsql';
CREATE TABLE account (
account_id SERIAL PRIMARY KEY,
username VARCHAR(25) UNIQUE CONSTRAINT username_regex CHECK (username ~ '^[a-zA-Z0-9]{2,25}$') NOT NULL,
email VARCHAR(254) NOT NULL,
password CHAR(60) NOT NULL, -- bcrypt
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
last_login TIMESTAMP
);
CREATE TRIGGER update_account_updated_at BEFORE UPDATE
ON account FOR EACH ROW EXECUTE PROCEDURE
update_updated_at_column();
@incyclum
Copy link
Author

incyclum commented Jun 7, 2017

See https://dba.stackexchange.com/q/68266 for storing an email in PostgreSQL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment