Re: simple auto-updating timestamp ?

From: "D(dot) Dante Lorenso" <dante(at)lorenso(dot)com>
To: Andreas <maps(dot)on(at)gmx(dot)net>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: simple auto-updating timestamp ?
Date: 2003-12-29 01:53:36
Message-ID: 3FEF8920.1070003@lorenso.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Andreas wrote:

> I suspect, this is a common issue for newbies.
> Is there a simple way to have an auto-updating timestamp like mysql has ?
>
> create table something (
> id int4,
> sometext text,
> update_ts timestamp(0),
> primary key (id)
> );
>
> Everytime this table gets updated the timestamp should be
> automatically refreshed to NOW() ?
> I hope someone could point me to an example.

You can do this by adding a trigger to your table. Just define the trigger
to be invoked on INSERT and UPDATE for your table. The trigger definition
would look something like this:

CREATE TRIGGER "trg_set_update_ts" BEFORE INSERT OR UPDATE
ON "public.something" FOR EACH ROW
EXECUTE PROCEDURE "public"."set_update_ts"();

Then, your function in PL/PGSQL that sets the update_ts to NOW() would look
something like this:

CREATE FUNCTION "public"."set_update_ts" () RETURNS trigger AS'
BEGIN
NEW.update_ts = NOW();
RETURN NEW;
END;
'LANGUAGE 'plpgsql' IMMUTABLE CALLED ON NULL INPUT SECURITY INVOKER;

Of course, this function would end up setting the update_ts to NOW() every
time you insert or update your table. And you could never set the value
to anything other than NOW() because your trigger would catch it and set it
back to NOW() again. If that's not exact, it'll at least point you in
the right direction.

Dante

----------
D. Dante Lorenso
dante(at)lorenso(dot)com

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Chris Travers 2003-12-29 01:56:35 Re: Is my MySQL Gaining ?
Previous Message Russ Schneider 2003-12-29 01:50:47 Re: Change onership of database and all tables? (fwd)