152

In MySQL, we can execute this where it updates the column 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?

2
  • afaik not as easy in PostgreSQL where you need a trigger: pointbeing.net/weblog/2008/03/… Commented Jun 24, 2009 at 0:58
  • 4
    @ErwinBrandstetter is the answer provided below still the best practice for autoupdating timestamps on 2018? Commented Aug 25, 2018 at 16:30

1 Answer 1

190

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();
Sign up to request clarification or add additional context in comments.

7 Comments

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.
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.
There is practically no performance penalty - at least in any sensible database.
Is there a way to give the column name that need to be updated as parameter to the function update_changetimestamp_column?
@womble It would likely be very useful to post an example of this. If I manage how to dynamically specify which column to update, I'll write it as an answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.