HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Add timestamp to field automatically in PostgreSQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlfieldautomaticallytimestampadd

Problem

I created a small database in PostgreSQL to manage the data for my thesis. I just started with Postgres, so this is probably a newbie question. I added a column in several tables, that is supposed to hold the last update of a certain field. One of these tables looks like this (The column relevant here would be lastupdate:

-- Drop table

-- DROP TABLE public.finds;

CREATE TABLE public.finds (
    id bigserial NOT NULL,
    id_investigations int8 NOT NULL,
    quote_short varchar NULL,
    "group" varchar NULL,
    "type" varchar NULL,
    subtype varchar NULL,
    description varchar NULL,
    "number" int4 NULL,
    certainty bool NULL,
    note varchar NULL,
    checked bool NULL,
    lastupdate timestamptz NULL,
    CONSTRAINT finds_check_group CHECK ((("group")::text = ANY ((ARRAY['Keramik'::character varying, 'Waffe'::character varying, 'Werkzeug'::character varying, 'Schmuck'::character varying])::text[]))),
    CONSTRAINT finds_pkey PRIMARY KEY (id),
    CONSTRAINT id_investigations FOREIGN KEY (id_investigations) REFERENCES investigations(id)
);

-- Permissions

ALTER TABLE public.finds OWNER TO postgres;
GRANT ALL ON TABLE public.finds TO postgres;


I would like the lastupdate to take the current timestamp upon edit. Is there a simple way to do this?

Solution

You could use a trigger like this:

CREATE FUNCTION last_upd_trig() RETURNS trigger
   LANGUAGE plpgsql AS
$BEGIN
   NEW.lastupdate := current_timestamp;
   RETURN NEW;
END;$;

CREATE TRIGGER last_upd_trigger
   BEFORE INSERT OR UPDATE ON finds
   FOR EACH ROW
   EXECUTE PROCEDURE last_upd_trig();

Code Snippets

CREATE FUNCTION last_upd_trig() RETURNS trigger
   LANGUAGE plpgsql AS
$$BEGIN
   NEW.lastupdate := current_timestamp;
   RETURN NEW;
END;$$;

CREATE TRIGGER last_upd_trigger
   BEFORE INSERT OR UPDATE ON finds
   FOR EACH ROW
   EXECUTE PROCEDURE last_upd_trig();

Context

StackExchange Database Administrators Q#257282, answer score: 5

Revisions (0)

No revisions yet.