Re: simple auto-updating timestamp ? - Mailing list pgsql-general

From D. Dante Lorenso
Subject Re: simple auto-updating timestamp ?
Date
Msg-id 3FEF8920.1070003@lorenso.com
Whole thread Raw
In response to simple auto-updating timestamp ?  (Andreas <maps.on@gmx.net>)
Responses Re: simple auto-updating timestamp ?
List 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@lorenso.com







pgsql-general by date:

Previous
From: Russ Schneider
Date:
Subject: Re: Change onership of database and all tables? (fwd)
Next
From: "Chris Travers"
Date:
Subject: Re: Is my MySQL Gaining ?