views:

1332

answers:

1

In Mysql, we can execute this where it updates the changetimestamp every time the row is changed.

create table ab (id int, changeTimestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP );

Is there something similar to do the above in Postgresql?

+10  A: 

Create a function that updates the changetimestamp column of a table like so:

CREATE OR REPLACE FUNCTION update_changetimestamp_column()
RETURNS TRIGGER AS $$
BEGIN
   NEW.changetimestamp = now(); 
   RETURN NEW;
END;
$$ language 'plpgsql';

Create a trigger on the table that calls the update_changetimestamp_column() function whenever an update occurs like so:

    CREATE TRIGGER update_ab_changetimestamp BEFORE UPDATE
    ON ab FOR EACH ROW EXECUTE PROCEDURE 
    update_changetimestamp_column();
Charles Ma
So, there is no other way of doing what I want except through a trigger? Because I would like to implement 'on update timestamp' for all of my tables possibly 300+. And I'm thinking that creating triggers might cause some performance issues.
bichonfrise74
As far as I know this is the standard way to do this in postgresql. When you write "on update current_timestamp" in mysql, it creates a trigger on the table in the background. The difference is that you're writing the trigger here manually instead of having it written for you.
Charles Ma
There is practically no performance penalty - at least in any sensible database.
depesz