Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update timestamp when row is updated in PostgreSQL

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?

like image 301
bichonfrise74 Avatar asked Jun 24 '09 00:06

bichonfrise74


People also ask

Should I use timestamp or Timestamptz?

Timestamp vs Timestamptz – What's the Difference? The big difference between these two data types is that timestamptz includes a timezone offset while timestamp does not. So it is important to decide for the timestamp you are storing whether the timezone is important to keep or not.

How is timestamp stored in PostgreSQL?

By casting "TimeStamp" to date you throw away the time part of the timestamp, so all values within one day will be considered equal and are returned in random order. It is by accident that the first rows appear in the order you desire. Don't cast to date in the ORDER BY clause if the time part is relevant for sorting.

Does Postgres support timestamp?

PostgreSQL provides you with two temporal data types for handling timestamp: timestamp : a timestamp without timezone one. timestamptz : timestamp with a timezone.


1 Answers

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(); 
like image 117
Charles Ma Avatar answered Oct 12 '22 16:10

Charles Ma