To automatically update the timestamp field in PostgresSQL whenever a new row is inserted, you can set the current_timestamp as its default value:
CREATE TABLE users (
id serial not null,
firstname varchar(100),
middlename varchar(100),
lastname varchar(100),
email varchar(200),
timestamp timestamp default current_timestamp
)
In addition to this, you might want to prevent anyone from updating this field in the future, and this can be done by creating an update trigger and applying it:
CREATE OR REPLACE FUNCTION stop_change_on_timestamp()
RETURNS trigger AS
$BODY$
BEGIN
-- always reset the timestamp to the old value ("actual creation time")
NEW.timestamp := OLD.timestamp;
RETURN NEW;
END;
$BODY$
CREATE TRIGGER prevent_timestamp_changes
BEFORE UPDATE
ON users
FOR EACH ROW
EXECUTE PROCEDURE stop_change_on_timestamp();
timestampis defined by the SQL spec as an abbreviation ofTIMESTAMP WITHOUT TIME ZONE. That is almost certainly not what you want, as explained by Postgres expert David E. Wheeler. The other type,TIMESTAMP WITH TIME ZONEis probably what you want, using any passed time zone offset information to adjust the date-time to UTC (but not actually storing that time zone info despite the type name).